rem
stringlengths 0
322k
| add
stringlengths 0
2.05M
| context
stringlengths 8
228k
|
---|---|---|
RunCommand(['%s/cros_run_vm_update' % self.crosutilsbin, '--update_image_path=%s' % image_path, '--vm_image_path=%s' % self.vm_image_path, '--snapshot', vm_graphics_flag, '--persist', '--kvm_pid=%s' % _KVM_PID_FILE, stateful_change_flag, '--src_image=%s' % self.source_image, ], enter_chroot=False) | (code, stdout, stderr) = RunCommandCaptureOutput([ '%s/cros_run_vm_update' % self.crosutilsbin, '--update_image_path=%s' % image_path, '--vm_image_path=%s' % self.vm_image_path, '--snapshot', vm_graphics_flag, '--persist', '--kvm_pid=%s' % _KVM_PID_FILE, stateful_change_flag, '--src_image=%s' % self.source_image, ]) if code != 0: raise UpdateException(code, stdout) def UpdateUsingPayload(self, update_path, stateful_change='old'): """Updates a remote image using image_to_live.sh.""" stateful_change_flag = self.GetStatefulChangeFlag(stateful_change) if self.source_image == base_image_path: self.source_image = self.vm_image_path (code, stdout, stderr) = RunCommandCaptureOutput([ '%s/cros_run_vm_update' % self.crosutilsbin, '--payload=%s' % update_path, '--vm_image_path=%s' % self.vm_image_path, '--snapshot', vm_graphics_flag, '--persist', '--kvm_pid=%s' % _KVM_PID_FILE, stateful_change_flag, '--src_image=%s' % self.source_image, ]) if code != 0: raise UpdateException(code, stdout) | def UpdateImage(self, image_path, stateful_change='old'): """Updates VM image with image_path.""" stateful_change_flag = self.GetStatefulChangeFlag(stateful_change) if self.source_image == base_image_path: self.source_image = self.vm_image_path |
raise subprocess.CalledProcessError(retcode, command, output=stdout) | _Print(stdout) raise subprocess.CalledProcessError(retcode, command) | def _SimpleRunCommand(command): """Runs a shell command and returns stdout back to caller.""" _Print(' + %s' % command) proc_handle = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True) stdout = proc_handle.communicate()[0] retcode = proc_handle.wait() if retcode != 0: raise subprocess.CalledProcessError(retcode, command, output=stdout) return stdout |
def _UprevFromRevisionList(buildroot, revision_list): | def _UprevFromRevisionList(buildroot, tracking_branch, revision_list): | def _UprevFromRevisionList(buildroot, revision_list): """Uprevs based on revision list.""" if not revision_list: Info('No packages found to uprev') return package_str = '' for package, revision in revision_list: package_str += package + ' ' package_str = package_str.strip() cwd = os.path.join(buildroot, 'src', 'scripts') RunCommand(['./cros_mark_as_stable', '--tracking_branch="cros/master"', '--packages="%s"' % package_str, 'commit'], cwd=cwd, enter_chroot=True) |
'--tracking_branch="cros/master"', | '--tracking_branch="%s"' % tracking_branch, | def _UprevFromRevisionList(buildroot, revision_list): """Uprevs based on revision list.""" if not revision_list: Info('No packages found to uprev') return package_str = '' for package, revision in revision_list: package_str += package + ' ' package_str = package_str.strip() cwd = os.path.join(buildroot, 'src', 'scripts') RunCommand(['./cros_mark_as_stable', '--tracking_branch="cros/master"', '--packages="%s"' % package_str, 'commit'], cwd=cwd, enter_chroot=True) |
def _UprevAllPackages(buildroot): | def _UprevAllPackages(buildroot, tracking_branch): | def _UprevAllPackages(buildroot): """Uprevs all packages that have been updated since last uprev.""" cwd = os.path.join(buildroot, 'src', 'scripts') RunCommand(['./cros_mark_as_stable', '--all', '--tracking_branch="cros/master"', 'commit'], cwd=cwd, enter_chroot=True) |
'--tracking_branch="cros/master"', 'commit'], | '--tracking_branch="%s"' % tracking_branch, 'commit'], | def _UprevAllPackages(buildroot): """Uprevs all packages that have been updated since last uprev.""" cwd = os.path.join(buildroot, 'src', 'scripts') RunCommand(['./cros_mark_as_stable', '--all', '--tracking_branch="cros/master"', 'commit'], cwd=cwd, enter_chroot=True) |
def _FullCheckout(buildroot, rw_checkout=True, retries=_DEFAULT_RETRIES): | def _FullCheckout(buildroot, tracking_branch, rw_checkout=True, retries=_DEFAULT_RETRIES, url='http://git.chromium.org/git/manifest'): | def _FullCheckout(buildroot, rw_checkout=True, retries=_DEFAULT_RETRIES): """Performs a full checkout and clobbers any previous checkouts.""" RunCommand(['sudo', 'rm', '-rf', buildroot]) MakeDir(buildroot, parents=True) RunCommand(['repo', 'init', '-u', 'http://git.chromium.org/git/manifest'], cwd=buildroot, input='\n\ny\n') RepoSync(buildroot, rw_checkout, retries) |
RunCommand(['repo', 'init', '-u', 'http://git.chromium.org/git/manifest'], cwd=buildroot, input='\n\ny\n') | branch = tracking_branch.split('/'); RunCommand(['repo', 'init', '-u', url, '-b', '%s' % branch[-1]], cwd=buildroot, input='\n\ny\n') | def _FullCheckout(buildroot, rw_checkout=True, retries=_DEFAULT_RETRIES): """Performs a full checkout and clobbers any previous checkouts.""" RunCommand(['sudo', 'rm', '-rf', buildroot]) MakeDir(buildroot, parents=True) RunCommand(['repo', 'init', '-u', 'http://git.chromium.org/git/manifest'], cwd=buildroot, input='\n\ny\n') RepoSync(buildroot, rw_checkout, retries) |
def _UprevPackages(buildroot, revisionfile, board): | def _UprevPackages(buildroot, tracking_branch, revisionfile, board): | def _UprevPackages(buildroot, revisionfile, board): """Uprevs a package based on given revisionfile. If revisionfile is set to None or does not resolve to an actual file, this function will uprev all packages. Keyword arguments: revisionfile -- string specifying a file that contains a list of revisions to uprev. """ # Purposefully set to None as it means Force Build was pressed. revisions = 'None' if (revisionfile): try: rev_file = open(revisionfile) revisions = rev_file.read() rev_file.close() except Exception, e: Warning('Error reading %s, revving all' % revisionfile) revisions = 'None' revisions = revisions.strip() # TODO(sosa): Un-comment once we close individual trees. # revisions == "None" indicates a Force Build. #if revisions != 'None': # print >> sys.stderr, 'CBUILDBOT Revision list found %s' % revisions # revision_list = _ParseRevisionString(revisions, # _CreateRepoDictionary(buildroot, board)) # _UprevFromRevisionList(buildroot, revision_list) #else: Info('CBUILDBOT Revving all') _UprevAllPackages(buildroot) |
_UprevAllPackages(buildroot) def _UprevPush(buildroot): | _UprevAllPackages(buildroot, tracking_branch) def _UprevPush(buildroot, tracking_branch): | def _UprevPackages(buildroot, revisionfile, board): """Uprevs a package based on given revisionfile. If revisionfile is set to None or does not resolve to an actual file, this function will uprev all packages. Keyword arguments: revisionfile -- string specifying a file that contains a list of revisions to uprev. """ # Purposefully set to None as it means Force Build was pressed. revisions = 'None' if (revisionfile): try: rev_file = open(revisionfile) revisions = rev_file.read() rev_file.close() except Exception, e: Warning('Error reading %s, revving all' % revisionfile) revisions = 'None' revisions = revisions.strip() # TODO(sosa): Un-comment once we close individual trees. # revisions == "None" indicates a Force Build. #if revisions != 'None': # print >> sys.stderr, 'CBUILDBOT Revision list found %s' % revisions # revision_list = _ParseRevisionString(revisions, # _CreateRepoDictionary(buildroot, board)) # _UprevFromRevisionList(buildroot, revision_list) #else: Info('CBUILDBOT Revving all') _UprevAllPackages(buildroot) |
'--tracking_branch="cros/master"', | '--tracking_branch="%s"' % tracking_branch, | def _UprevPush(buildroot): """Pushes uprev changes to the main line.""" cwd = os.path.join(buildroot, 'src', 'scripts') RunCommand(['./cros_mark_as_stable', '--srcroot=..', '--tracking_branch="cros/master"', '--push_options="--bypass-hooks -f"', 'push'], cwd=cwd) |
_FullCheckout(buildroot) | _FullCheckout(buildroot, tracking_branch, url=options.url) | def main(): # Parse options usage = "usage: %prog [options] cbuildbot_config" parser = optparse.OptionParser(usage=usage) parser.add_option('-r', '--buildroot', help='root directory where build occurs', default=".") parser.add_option('-n', '--buildnumber', help='build number', type='int', default=0) parser.add_option('-f', '--revisionfile', help='file where new revisions are stored') parser.add_option('--clobber', action='store_true', dest='clobber', default=False, help='Clobbers an old checkout before syncing') parser.add_option('--debug', action='store_true', dest='debug', default=False, help='Override some options to run as a developer.') (options, args) = parser.parse_args() buildroot = options.buildroot revisionfile = options.revisionfile if len(args) >= 1: buildconfig = _GetConfig(args[-1]) else: Warning('Missing configuration description') parser.print_usage() sys.exit(1) try: _PreFlightRinse(buildroot) if options.clobber or not os.path.isdir(buildroot): _FullCheckout(buildroot) else: _IncrementalCheckout(buildroot) chroot_path = os.path.join(buildroot, 'chroot') if not os.path.isdir(chroot_path): _MakeChroot(buildroot) boardpath = os.path.join(chroot_path, 'build', buildconfig['board']) if not os.path.isdir(boardpath): _SetupBoard(buildroot, board=buildconfig['board']) if buildconfig['uprev']: _UprevPackages(buildroot, revisionfile, board=buildconfig['board']) _EnableLocalAccount(buildroot) _Build(buildroot) if buildconfig['unittests']: _RunUnitTests(buildroot) _BuildImage(buildroot) if buildconfig['smoke_bvt']: _BuildVMImageForTesting(buildroot) _RunSmokeSuite(buildroot) if buildconfig['uprev']: # Don't push changes for developers. if not options.debug: if buildconfig['master']: # Master bot needs to check if the other slaves completed. if cbuildbot_comm.HaveSlavesCompleted(config): _UprevPush(buildroot) else: Die('CBUILDBOT - One of the slaves has failed!!!') else: # Publish my status to the master if its expecting it. if buildconfig['important']: cbuildbot_comm.PublishStatus(cbuildbot_comm.STATUS_BUILD_COMPLETE) except: # Send failure to master bot. if not buildconfig['master'] and buildconfig['important']: cbuildbot_comm.PublishStatus(cbuildbot_comm.STATUS_BUILD_FAILED) raise |
_UprevPackages(buildroot, revisionfile, board=buildconfig['board']) | _UprevPackages(buildroot, tracking_branch, revisionfile, board=buildconfig['board']) | def main(): # Parse options usage = "usage: %prog [options] cbuildbot_config" parser = optparse.OptionParser(usage=usage) parser.add_option('-r', '--buildroot', help='root directory where build occurs', default=".") parser.add_option('-n', '--buildnumber', help='build number', type='int', default=0) parser.add_option('-f', '--revisionfile', help='file where new revisions are stored') parser.add_option('--clobber', action='store_true', dest='clobber', default=False, help='Clobbers an old checkout before syncing') parser.add_option('--debug', action='store_true', dest='debug', default=False, help='Override some options to run as a developer.') (options, args) = parser.parse_args() buildroot = options.buildroot revisionfile = options.revisionfile if len(args) >= 1: buildconfig = _GetConfig(args[-1]) else: Warning('Missing configuration description') parser.print_usage() sys.exit(1) try: _PreFlightRinse(buildroot) if options.clobber or not os.path.isdir(buildroot): _FullCheckout(buildroot) else: _IncrementalCheckout(buildroot) chroot_path = os.path.join(buildroot, 'chroot') if not os.path.isdir(chroot_path): _MakeChroot(buildroot) boardpath = os.path.join(chroot_path, 'build', buildconfig['board']) if not os.path.isdir(boardpath): _SetupBoard(buildroot, board=buildconfig['board']) if buildconfig['uprev']: _UprevPackages(buildroot, revisionfile, board=buildconfig['board']) _EnableLocalAccount(buildroot) _Build(buildroot) if buildconfig['unittests']: _RunUnitTests(buildroot) _BuildImage(buildroot) if buildconfig['smoke_bvt']: _BuildVMImageForTesting(buildroot) _RunSmokeSuite(buildroot) if buildconfig['uprev']: # Don't push changes for developers. if not options.debug: if buildconfig['master']: # Master bot needs to check if the other slaves completed. if cbuildbot_comm.HaveSlavesCompleted(config): _UprevPush(buildroot) else: Die('CBUILDBOT - One of the slaves has failed!!!') else: # Publish my status to the master if its expecting it. if buildconfig['important']: cbuildbot_comm.PublishStatus(cbuildbot_comm.STATUS_BUILD_COMPLETE) except: # Send failure to master bot. if not buildconfig['master'] and buildconfig['important']: cbuildbot_comm.PublishStatus(cbuildbot_comm.STATUS_BUILD_FAILED) raise |
_UprevPush(buildroot) | _UprevPush(buildroot, tracking_branch) | def main(): # Parse options usage = "usage: %prog [options] cbuildbot_config" parser = optparse.OptionParser(usage=usage) parser.add_option('-r', '--buildroot', help='root directory where build occurs', default=".") parser.add_option('-n', '--buildnumber', help='build number', type='int', default=0) parser.add_option('-f', '--revisionfile', help='file where new revisions are stored') parser.add_option('--clobber', action='store_true', dest='clobber', default=False, help='Clobbers an old checkout before syncing') parser.add_option('--debug', action='store_true', dest='debug', default=False, help='Override some options to run as a developer.') (options, args) = parser.parse_args() buildroot = options.buildroot revisionfile = options.revisionfile if len(args) >= 1: buildconfig = _GetConfig(args[-1]) else: Warning('Missing configuration description') parser.print_usage() sys.exit(1) try: _PreFlightRinse(buildroot) if options.clobber or not os.path.isdir(buildroot): _FullCheckout(buildroot) else: _IncrementalCheckout(buildroot) chroot_path = os.path.join(buildroot, 'chroot') if not os.path.isdir(chroot_path): _MakeChroot(buildroot) boardpath = os.path.join(chroot_path, 'build', buildconfig['board']) if not os.path.isdir(boardpath): _SetupBoard(buildroot, board=buildconfig['board']) if buildconfig['uprev']: _UprevPackages(buildroot, revisionfile, board=buildconfig['board']) _EnableLocalAccount(buildroot) _Build(buildroot) if buildconfig['unittests']: _RunUnitTests(buildroot) _BuildImage(buildroot) if buildconfig['smoke_bvt']: _BuildVMImageForTesting(buildroot) _RunSmokeSuite(buildroot) if buildconfig['uprev']: # Don't push changes for developers. if not options.debug: if buildconfig['master']: # Master bot needs to check if the other slaves completed. if cbuildbot_comm.HaveSlavesCompleted(config): _UprevPush(buildroot) else: Die('CBUILDBOT - One of the slaves has failed!!!') else: # Publish my status to the master if its expecting it. if buildconfig['important']: cbuildbot_comm.PublishStatus(cbuildbot_comm.STATUS_BUILD_COMPLETE) except: # Send failure to master bot. if not buildconfig['master'] and buildconfig['important']: cbuildbot_comm.PublishStatus(cbuildbot_comm.STATUS_BUILD_FAILED) raise |
def _MarkChromeAsStable(buildroot, tracking_branch, chrome_rev): | def _MarkChromeAsStable(buildroot, tracking_branch, chrome_rev, board): | def _MarkChromeAsStable(buildroot, tracking_branch, chrome_rev): """Returns the portage atom for the revved chrome ebuild - see man emerge.""" cwd = os.path.join(buildroot, 'src', 'scripts') portage_atom_string = RunCommand(['bin/cros_mark_chrome_as_stable', '--tracking_branch=%s' % tracking_branch, chrome_rev], cwd=cwd, redirect_stdout=True, enter_chroot=True).rstrip() if not portage_atom_string: Info('Found nothing to rev.') return None else: return portage_atom_string.split('=')[1] |
return portage_atom_string.split('=')[1] | chrome_atom = portage_atom_string.split('=')[1] RunCommand(['sudo', 'tee', CHROME_KEYWORDS_FILE % {'board': board}], input='=%s\n' % chrome_atom, enter_chroot=True, cwd=cwd) return chrome_atom | def _MarkChromeAsStable(buildroot, tracking_branch, chrome_rev): """Returns the portage atom for the revved chrome ebuild - see man emerge.""" cwd = os.path.join(buildroot, 'src', 'scripts') portage_atom_string = RunCommand(['bin/cros_mark_chrome_as_stable', '--tracking_branch=%s' % tracking_branch, chrome_rev], cwd=cwd, redirect_stdout=True, enter_chroot=True).rstrip() if not portage_atom_string: Info('Found nothing to rev.') return None else: return portage_atom_string.split('=')[1] |
RunCommand(['ACCEPT_KEYWORDS="* ~*"', 'emerge-%s' % board, | RunCommand(['emerge-%s' % board, | def _BuildChrome(buildroot, board, chrome_atom_to_build): """Wrapper for emerge call to build Chrome.""" cwd = os.path.join(buildroot, 'src', 'scripts') RunCommand(['ACCEPT_KEYWORDS="* ~*"', 'emerge-%s' % board, '=%s' % chrome_atom_to_build], cwd=cwd, enter_chroot=True) |
options.chrome_rev) | options.chrome_rev, board) | def main(): # Parse options usage = "usage: %prog [options] cbuildbot_config" parser = optparse.OptionParser(usage=usage) parser.add_option('-a', '--acl', default='private', help='ACL to set on GSD archives') parser.add_option('-r', '--buildroot', help='root directory where build occurs', default=".") parser.add_option('-n', '--buildnumber', help='build number', type='int', default=0) parser.add_option('--chrome_rev', default=None, type='string', dest='chrome_rev', help=('Chrome_rev of type [tot|latest_release|' 'sticky_release]')) parser.add_option('-g', '--gsutil', default='', help='Location of gsutil') parser.add_option('-c', '--gsutil_archive', default='', help='Datastore archive location') parser.add_option('--clobber', action='store_true', dest='clobber', default=False, help='Clobbers an old checkout before syncing') parser.add_option('--debug', action='store_true', dest='debug', default=False, help='Override some options to run as a developer.') parser.add_option('--noprebuilts', action='store_false', dest='prebuilts', help="Don't upload prebuilts.") parser.add_option('--nosync', action='store_false', dest='sync', default=True, help="Don't sync before building.") parser.add_option('--notests', action='store_false', dest='tests', default=True, help='Override values from buildconfig and run no tests.') parser.add_option('-f', '--revisionfile', help='file where new revisions are stored') parser.add_option('-t', '--tracking-branch', dest='tracking_branch', default='cros/master', help='Run the buildbot on a branch') parser.add_option('-u', '--url', dest='url', default='http://git.chromium.org/git/manifest', help='Run the buildbot on internal manifest') (options, args) = parser.parse_args() buildroot = os.path.abspath(options.buildroot) revisionfile = options.revisionfile tracking_branch = options.tracking_branch chrome_atom_to_build = None if len(args) >= 1: buildconfig = _GetConfig(args[-1]) else: Warning('Missing configuration description') parser.print_usage() sys.exit(1) try: # Calculate list of overlay directories. rev_overlays = _ResolveOverlays(buildroot, buildconfig['rev_overlays']) push_overlays = _ResolveOverlays(buildroot, buildconfig['push_overlays']) # We cannot push to overlays that we don't rev. assert set(push_overlays).issubset(set(rev_overlays)) # Either has to be a master or not have any push overlays. assert buildconfig['master'] or not push_overlays board = buildconfig['board'] old_binhost = None _PreFlightRinse(buildroot, buildconfig['board'], tracking_branch, rev_overlays) chroot_path = os.path.join(buildroot, 'chroot') boardpath = os.path.join(chroot_path, 'build', board) if options.sync: if options.clobber or not os.path.isdir(buildroot): _FullCheckout(buildroot, tracking_branch, url=options.url) else: old_binhost = _GetPortageEnvVar(buildroot, board, _FULL_BINHOST) _IncrementalCheckout(buildroot) new_binhost = _GetPortageEnvVar(buildroot, board, _FULL_BINHOST) emptytree = (old_binhost and old_binhost != new_binhost) # Check that all overlays can be found. for path in rev_overlays: if not os.path.isdir(path): Die('Missing overlay: %s' % path) if not options.chrome_rev: _DumpManifest(buildroot, options.url) if not os.path.isdir(chroot_path): _MakeChroot(buildroot) if not os.path.isdir(boardpath): _SetupBoard(buildroot, board=buildconfig['board']) # Perform uprev. If chrome_uprev is set, rev Chrome ebuilds. if options.chrome_rev: chrome_atom_to_build = _MarkChromeAsStable(buildroot, tracking_branch, options.chrome_rev) # If we found nothing to rev, we're done here. if not chrome_atom_to_build: return elif buildconfig['uprev']: _UprevPackages(buildroot, tracking_branch, revisionfile, buildconfig['board'], rev_overlays) _EnableLocalAccount(buildroot) # Doesn't rebuild without acquiring more source. if options.sync: _Build(buildroot, emptytree) if chrome_atom_to_build: _BuildChrome(buildroot, buildconfig['board'], chrome_atom_to_build) if buildconfig['unittests'] and options.tests: _RunUnitTests(buildroot) _BuildImage(buildroot) if buildconfig['smoke_bvt'] and options.tests: _BuildVMImageForTesting(buildroot) test_results_dir = '/tmp/run_remote_tests.%s' % options.buildnumber try: _RunSmokeSuite(buildroot, test_results_dir) finally: if not options.debug: archive_full_path = os.path.join(options.gsutil_archive, str(options.buildnumber)) _ArchiveTestResults(buildroot, buildconfig['board'], test_results_dir=test_results_dir, gsutil=options.gsutil, archive_dir=archive_full_path, acl=options.acl) if buildconfig['uprev']: # Don't push changes for developers. if buildconfig['master']: # Master bot needs to check if the other slaves completed. if cbuildbot_comm.HaveSlavesCompleted(config): if not options.debug and options.prebuilts: _UploadPrebuilts(buildroot, board, buildconfig['rev_overlays'], [new_binhost]) _UprevPush(buildroot, tracking_branch, buildconfig['board'], push_overlays, options.debug) else: Die('CBUILDBOT - One of the slaves has failed!!!') else: # Publish my status to the master if its expecting it. if buildconfig['important'] and not options.debug: cbuildbot_comm.PublishStatus(cbuildbot_comm.STATUS_BUILD_COMPLETE) except: # Send failure to master bot. if not buildconfig['master'] and buildconfig['important']: cbuildbot_comm.PublishStatus(cbuildbot_comm.STATUS_BUILD_FAILED) raise |
_RunCommand('git rebase origin/master') | _RunCommand('git rebase %s' % gflags.FLAGS.tracking_branch) | def _PushChange(): """Pushes changes to the git repository. Pushes locals commits from calls to CommitChange to the remote git repository specified by os.pwd. Raises: OSError: Error occurred while pushing. """ # TODO(sosa) - Add logic for buildbot to check whether other slaves have # completed and push this change only if they have. # Sanity check to make sure we're on a stabilizing branch before pushing. if not _CheckOnStabilizingBranch(): generate_test_report.Die('Expected %s to be on branch "%s"' % (os.getcwd(), _STABLE_BRANCH_NAME)) _RunCommand('git cl upload --desc_from_logs -m "%s"' % 'Marking set of ebuilds as stable') _RunCommand('git remote update') _RunCommand('git rebase origin/master') _RunCommand('git cl push %s' % gflags.FLAGS.push_options) |
elif re.match('.*?-.*?_.*', target): | elif re.match('.*?_.*', target): | def DetermineMakeConfFile(target): """Determine the make.conf file that needs to be updated for prebuilts. Args: target: String representation of the board. This includes host and board targets Returns A string path to a make.conf file to be updated. """ if _HOST_TARGET == target: # We are host. # Without more examples of hosts this is a kludge for now. # TODO(Scottz): as new host targets come online expand this to # work more like boards. make_path = _PREBUILT_MAKE_CONF[target] elif re.match('.*?-.*?_.*', target): # We are a board variant overlay_str = 'overlay-variant-%s' % target.replace('_', '-') make_path = os.path.join(_BINHOST_BASE_DIR, overlay_str, 'make.conf') elif re.match('.*?-\w+', target): overlay_str = 'overlay-%s' % target make_path = os.path.join(_BINHOST_BASE_DIR, overlay_str, 'make.conf') else: raise UnknownBoardFormat('Unknown format: %s' % target) return os.path.join(make_path) |
self.UpdateImage(target_image_path) | try: self.UpdateImage(target_image_path) except: if self.use_delta_updates: Warning('Delta update failed, disabling delta updates and retrying.') self.use_delta_updates = False self.source_image = '' self.UpdateImage(target_image_path) else: raise | def testFullUpdateKeepStateful(self): """Tests if we can update normally. |
"""Build image and modify mini omaha config. | """Build factory packages and modify mini omaha config. Args: signed_image: signed image base_image: base image fw_updater: firmware updater folder: destination folder to write packages board: platform to build | def build_factory_packages(signed_image, base_image, fw_updater, folder, board): """Build image and modify mini omaha config. """ cmd = ('./make_factory_package.sh --release %s --factory %s' ' --firmware_updater %s --subfolder %s --board %s' % (signed_image, base_image, fw_updater, folder, board)) print 'Building factory packages: %s' % cmd build_packages_process = KillableProcess(cmd, cwd=SCRIPTS_DIR) build_packages_process.start() |
' --firmware_updater %s --subfolder %s --board %s' % (signed_image, base_image, fw_updater, folder, board)) | ' --subfolder %s --board %s' % (signed_image, base_image, folder, board)) if fw_updater: cmd = '%s --firmware_updater %s' % (cmd, fw_updater) else: print ('No --firmware_updater specified. Not including firmware shellball.') | def build_factory_packages(signed_image, base_image, fw_updater, folder, board): """Build image and modify mini omaha config. """ cmd = ('./make_factory_package.sh --release %s --factory %s' ' --firmware_updater %s --subfolder %s --board %s' % (signed_image, base_image, fw_updater, folder, board)) print 'Building factory packages: %s' % cmd build_packages_process = KillableProcess(cmd, cwd=SCRIPTS_DIR) build_packages_process.start() |
if not FLAGS.firmware_updater: exit('No --firmware_updater specified.') | if FLAGS.firmware_updater: assert_is_file(FLAGS.firmware_updater, 'Invalid or missing firmware updater.') | def main(argv): try: argv = FLAGS(argv) except gflags.FlagsError, e: print '%s\nUsage: %s ARGS\n%s' % (e, sys.argv[0], FLAGS) sys.exit(1) if not FLAGS.base_image: exit('No --base_image specified.') if not FLAGS.firmware_updater: exit('No --firmware_updater specified.') assert_is_file(FLAGS.base_image, 'Invalid or missing base image.') assert_is_file(FLAGS.firmware_updater, 'Invalid or missing firmware updater.') signed_image = os.path.join(os.path.dirname(FLAGS.base_image), '%s_ssd_signed.bin' % FLAGS.board) setup_board(FLAGS.board) sign_build(FLAGS.base_image, signed_image) build_factory_packages(signed_image, FLAGS.base_image, FLAGS.firmware_updater, folder=FLAGS.board, board=FLAGS.board) start_devserver() |
assert_is_file(FLAGS.firmware_updater, 'Invalid or missing firmware updater.') | def main(argv): try: argv = FLAGS(argv) except gflags.FlagsError, e: print '%s\nUsage: %s ARGS\n%s' % (e, sys.argv[0], FLAGS) sys.exit(1) if not FLAGS.base_image: exit('No --base_image specified.') if not FLAGS.firmware_updater: exit('No --firmware_updater specified.') assert_is_file(FLAGS.base_image, 'Invalid or missing base image.') assert_is_file(FLAGS.firmware_updater, 'Invalid or missing firmware updater.') signed_image = os.path.join(os.path.dirname(FLAGS.base_image), '%s_ssd_signed.bin' % FLAGS.board) setup_board(FLAGS.board) sign_build(FLAGS.base_image, signed_image) build_factory_packages(signed_image, FLAGS.base_image, FLAGS.firmware_updater, folder=FLAGS.board, board=FLAGS.board) start_devserver() |
|
def Setup(filehash, filesize): | def Setup(filehash, filesha256, filesize): | def Setup(filehash, filesize): PingUpdateResponse.file_hash = filehash PingUpdateResponse.file_size = filesize |
self.file_hash, self.file_size)) | self.file_hash, self.file_sha256, self.file_size)) | def Reply(self, handler, send_content=True, post_data=None): """Return (using StringResponse) an XML reply to ForcedUpdate clients.""" |
chrome_version_re = re.compile('^[0-9]\..*') | chrome_version_re = re.compile('^[0-9]+\..*') | def _GetLatestRelease(branch=None): """Gets the latest release version from the buildspec_url for the branch. Args: branch: If set, gets the latest release for branch, otherwise latest release. Returns: Latest version string. """ buildspec_url = 'http://src.chromium.org/svn/releases' svn_ls = RunCommand(['svn', 'ls', buildspec_url], redirect_stdout=True) sorted_ls = RunCommand(['sort', '--version-sort'], input=svn_ls, redirect_stdout=True) if branch: chrome_version_re = re.compile('^%s\.\d+.*' % branch) else: chrome_version_re = re.compile('^[0-9]\..*') for chrome_version in sorted_ls.splitlines(): if chrome_version_re.match(chrome_version): current_version = chrome_version return current_version.rstrip('/') |
if not ebuild.is_stable: | if '9999' in ebuild.version: | def FindChromeCandidates(overlay_dir): """Return a tuple of chrome's unstable ebuild and stable ebuilds. Args: overlay_dir: The path to chrome's portage overlay dir. Returns: Tuple [unstable_ebuild, stable_ebuilds]. Raises: Exception: if no unstable ebuild exists for Chrome. """ stable_ebuilds = [] unstable_ebuilds = [] for path in [ os.path.join(overlay_dir, entry) for entry in os.listdir(overlay_dir)]: if path.endswith('.ebuild'): ebuild = ChromeEBuild(path) if not ebuild.chrome_version: Warning('Poorly formatted ebuild found at %s' % path) else: if not ebuild.is_stable: unstable_ebuilds.append(ebuild) else: stable_ebuilds.append(ebuild) # Apply some sanity checks. if not unstable_ebuilds: raise Exception('Missing 9999 ebuild for %s' % overlay_dir) if not stable_ebuilds: Warning('Missing stable ebuild for %s' % overlay_dir) return cros_mark_as_stable.BestEBuild(unstable_ebuilds), stable_ebuilds |
def testFullUpdateWipeStateful(self): | def NotestFullUpdateWipeStateful(self): """Tests if we can update after cleaning the stateful partition. This test checks that we can update successfully after wiping the stateful partition. """ | def testFullUpdateWipeStateful(self): # Prepare and verify the base image has been prepared correctly. self.PrepareBase() self.VerifyImage() |
AUTest.setUp(self) | def setUp(self): """Unit test overriden method. Is called before every test.""" |
|
RunCommand(['%s/image_to_vm.sh' % _SCRIPTS_DIR, | RunCommand(['%s/image_to_vm.sh' % self.crosutils, | def PrepareBase(self): """Creates an update-able VM based on base image.""" |
stateful_change_flag = '' if stateful_change: stateful_change_flag = '--stateful_flags=%s' % stateful_change RunCommand(['%s/cros_run_vm_update' % os.path.dirname(__file__), | stateful_change_flag = self.GetStatefulChangeFlag(stateful_change) RunCommand(['%s/cros_run_vm_update' % self.crosutilsbin, | def UpdateImage(self, image_path, stateful_change='old'): """Updates VM image with image_path.""" |
RunCommand(['%s/cros_run_vm_test' % os.path.dirname(__file__), | RunCommand(['%s/cros_run_vm_test' % self.crosutilsbin, | def VerifyImage(self): """Runs vm smoke suite to verify image.""" |
], error_ok=True, enter_chroot=False) | ], error_ok=False, enter_chroot=False) | def VerifyImage(self): """Runs vm smoke suite to verify image.""" |
help='path to the target image') | help='path to the target image.') | def VerifyImage(self): """Runs vm smoke suite to verify image.""" |
help='board for the images') | help='board for the images.') parser.add_option('-p', '--type', default='vm', help='type of test to run: [vm, real]. Default: vm.') parser.add_option('-m', '--remote', help='Remote address for real test.') | def VerifyImage(self): """Runs vm smoke suite to verify image.""" |
unittest.main() | if options.type == 'vm': suite = unittest.TestLoader().loadTestsFromTestCase(VirtualAUTest) unittest.TextTestRunner(verbosity=2).run(suite) elif options.type == 'real': if not options.remote: parser.error('Real tests require a remote test machine.') else: remote = options.remote suite = unittest.TestLoader().loadTestsFromTestCase(RealAUTest) unittest.TextTestRunner(verbosity=2).run(suite) else: parser.error('Could not parse harness type %s.' % options.type) | def VerifyImage(self): """Runs vm smoke suite to verify image.""" |
def _GitCleanup(buildroot, board): | def _GitCleanup(buildroot, board, tracking_branch): | def _GitCleanup(buildroot, board): """Clean up git branch after previous uprev attempt.""" cwd = os.path.join(buildroot, 'src', 'scripts') if os.path.exists(cwd): RunCommand(['./cros_mark_as_stable', '--srcroot=..', '--board=%s' % board, '--tracking_branch="cros/master"', 'clean'], cwd=cwd, error_ok=True) |
'--tracking_branch="cros/master"', 'clean'], | '--tracking_branch="%s"' % tracking_branch, 'clean'], | def _GitCleanup(buildroot, board): """Clean up git branch after previous uprev attempt.""" cwd = os.path.join(buildroot, 'src', 'scripts') if os.path.exists(cwd): RunCommand(['./cros_mark_as_stable', '--srcroot=..', '--board=%s' % board, '--tracking_branch="cros/master"', 'clean'], cwd=cwd, error_ok=True) |
def _PreFlightRinse(buildroot, board): | def _PreFlightRinse(buildroot, board, tracking_branch): | def _PreFlightRinse(buildroot, board): """Cleans up any leftover state from previous runs.""" _GitCleanup(buildroot, board) _CleanUpMountPoints(buildroot) RunCommand(['sudo', 'killall', 'kvm'], error_ok=True) |
_GitCleanup(buildroot, board) | _GitCleanup(buildroot, board, tracking_branch) | def _PreFlightRinse(buildroot, board): """Cleans up any leftover state from previous runs.""" _GitCleanup(buildroot, board) _CleanUpMountPoints(buildroot) RunCommand(['sudo', 'killall', 'kvm'], error_ok=True) |
_PreFlightRinse(buildroot, buildconfig['board']) | _PreFlightRinse(buildroot, buildconfig['board'], tracking_branch) | def main(): # Parse options usage = "usage: %prog [options] cbuildbot_config" parser = optparse.OptionParser(usage=usage) parser.add_option('-r', '--buildroot', help='root directory where build occurs', default=".") parser.add_option('-n', '--buildnumber', help='build number', type='int', default=0) parser.add_option('-f', '--revisionfile', help='file where new revisions are stored') parser.add_option('--clobber', action='store_true', dest='clobber', default=False, help='Clobbers an old checkout before syncing') parser.add_option('--debug', action='store_true', dest='debug', default=False, help='Override some options to run as a developer.') parser.add_option('-t', '--tracking-branch', dest='tracking_branch', default='cros/master', help='Run the buildbot on a branch') parser.add_option('-u', '--url', dest='url', default='http://git.chromium.org/git/manifest', help='Run the buildbot on internal manifest') (options, args) = parser.parse_args() buildroot = options.buildroot revisionfile = options.revisionfile tracking_branch = options.tracking_branch if len(args) >= 1: buildconfig = _GetConfig(args[-1]) else: Warning('Missing configuration description') parser.print_usage() sys.exit(1) try: _PreFlightRinse(buildroot, buildconfig['board']) if options.clobber or not os.path.isdir(buildroot): _FullCheckout(buildroot, tracking_branch, url=options.url) else: _IncrementalCheckout(buildroot) chroot_path = os.path.join(buildroot, 'chroot') if not os.path.isdir(chroot_path): _MakeChroot(buildroot) boardpath = os.path.join(chroot_path, 'build', buildconfig['board']) if not os.path.isdir(boardpath): _SetupBoard(buildroot, board=buildconfig['board']) if buildconfig['uprev']: _UprevPackages(buildroot, tracking_branch, revisionfile, board=buildconfig['board']) _EnableLocalAccount(buildroot) _Build(buildroot) if buildconfig['unittests']: _RunUnitTests(buildroot) _BuildImage(buildroot) if buildconfig['smoke_bvt']: _BuildVMImageForTesting(buildroot) test_results_dir = '/tmp/run_remote_tests.%s' % options.buildnumber try: _RunSmokeSuite(buildroot, test_results_dir) finally: _ArchiveTestResults(buildroot, buildconfig['board'], archive_dir=options.buildnumber, test_results_dir=test_results_dir) if buildconfig['uprev']: # Don't push changes for developers. if not options.debug: if buildconfig['master']: # Master bot needs to check if the other slaves completed. if cbuildbot_comm.HaveSlavesCompleted(config): _UprevPush(buildroot, tracking_branch, buildconfig['board']) else: Die('CBUILDBOT - One of the slaves has failed!!!') else: # Publish my status to the master if its expecting it. if buildconfig['important']: cbuildbot_comm.PublishStatus(cbuildbot_comm.STATUS_BUILD_COMPLETE) except: # Send failure to master bot. if not buildconfig['master'] and buildconfig['important']: cbuildbot_comm.PublishStatus(cbuildbot_comm.STATUS_BUILD_FAILED) raise |
merge_branch = _GitBranch(merge_branch_name) | merge_branch = GitBranch(merge_branch_name) | def PushChange(stable_branch, tracking_branch): """Pushes commits in the stable_branch to the remote git repository. Pushes locals commits from calls to CommitChange to the remote git repository specified by current working directory. Args: stable_branch: The local branch with commits we want to push. tracking_branch: The tracking branch of the local branch. Raises: OSError: Error occurred while pushing. """ num_retries = 5 # Sanity check to make sure we're on a stabilizing branch before pushing. if not _CheckOnStabilizingBranch(stable_branch): Info('Not on branch %s so no work found to push. Exiting' % stable_branch) return description = _SimpleRunCommand('git log --format=format:%s%n%n%b ' + tracking_branch) description = 'Marking set of ebuilds as stable\n\n%s' % description merge_branch_name = 'merge_branch' for push_try in range(num_retries + 1): try: _SimpleRunCommand('git remote update') merge_branch = _GitBranch(merge_branch_name) merge_branch.CreateBranch() if not merge_branch.Exists(): Die('Unable to create merge branch.') _SimpleRunCommand('git merge --squash %s' % _STABLE_BRANCH_NAME) _SimpleRunCommand('git commit -m "%s"' % description) # Ugh. There has got to be an easier way to push to a tracking branch _SimpleRunCommand('git config push.default tracking') _SimpleRunCommand('git push') break except: if push_try < num_retries: Warning('Failed to push change, performing retry (%s/%s)' % ( push_try + 1, num_retries)) else: raise |
for path in paths: assert ':' not in path, 'Overlay must not contain colons: %s' % path if not os.path.isdir(path): Die('Missing overlay: %s' % path) | def _ResolveOverlays(buildroot, overlays): """Return the list of overlays to use for a given buildbot. Args: buildroot: The root directory where the build occurs. Must be an absolute path. overlays: A string describing which overlays you want. 'private': Just the private overlay. 'public': Just the public overlay. 'both': Both the public and private overlays. """ public_overlay = '%s/src/third_party/chromiumos-overlay' % buildroot private_overlay = '%s/src/private-overlays/chromeos-overlay' % buildroot if overlays == 'private': paths = [private_overlay] elif overlays == 'public': paths = [public_overlay] elif overlays == 'both': paths = [public_overlay, private_overlay] else: Die('Incorrect overlay configuration: %s' % overlays) for path in paths: assert ':' not in path, 'Overlay must not contain colons: %s' % path if not os.path.isdir(path): Die('Missing overlay: %s' % path) return paths |
|
redirect_file.write('CROS_WORKON_COMMIT="%s"' % commit_id) | redirect_file.write('CROS_WORKON_COMMIT="%s"\n' % commit_id) | def RevEBuild(self, commit_id="", redirect_file=None): """Revs an ebuild given the git commit id. |
cwd = os.path.join(buildroot, 'src', 'scripts') | cwd = os.path.join(buildroot, 'src', 'third_party', 'chromiumos-overlay', 'chromeos', 'config') | def _GetChromeOSVersion(buildroot): """Returns the tuple version of the Chrome OS version of the buildroot.""" cwd = os.path.join(buildroot, 'src', 'scripts') version_cmd = './chromeos_version.sh' output = RunCommand(version_cmd, cwd=cwd, redirect_stdout=True, redirect_stderr=True) version_re = re.compile('\s+CHROMEOS_VERSION_STRING=' '(\d+)\.(\d+)\.(\d+)\.(\w+)') for line in output.splitlines(): match = version_re.match(line) if match: return match.group(1), match.group(2), match.group(3), match.group(4) raise Exception('Chrome OS version not found.') |
cmd = 'python devserver.py' | cmd = 'python devserver.py --factory_config miniomaha.conf' | def start_devserver(): """Starts devserver.""" cmd = 'python devserver.py' print 'Running command: %s' % cmd devserver_process = KillableProcess(cmd, cwd=DEVSERVER_DIR) devserver_process.start(wait=False) |
start_devserver() | if FLAGS.start_devserver: start_devserver() | def main(argv): try: argv = FLAGS(argv) except gflags.FlagsError, e: print '%s\nUsage: %s ARGS\n%s' % (e, sys.argv[0], FLAGS) sys.exit(1) if not FLAGS.base_image: exit('No --base_image specified.') if FLAGS.firmware_updater: assert_is_file(FLAGS.firmware_updater, 'Invalid or missing firmware updater.') assert_is_file(FLAGS.base_image, 'Invalid or missing base image.') signed_image = os.path.join(os.path.dirname(FLAGS.base_image), '%s_ssd_signed.bin' % FLAGS.board) setup_board(FLAGS.board) sign_build(FLAGS.base_image, signed_image) build_factory_packages(signed_image, FLAGS.base_image, FLAGS.firmware_updater, folder=FLAGS.board, board=FLAGS.board) start_devserver() |
def execute( self, application, *options ): | def execute( self, application, *options, **kwargs ): | def execute( self, application, *options ): """Execute a dialplan application with given options |
"|".join([ | delimiter.join([ | def execute( self, application, *options ): """Execute a dialplan application with given options |
"""Send a null operation to the server | """Send a null operation to the server. Any message sent will be printed to the CLI. | def noop( self, message=None ): """Send a null operation to the server |
command = '''GET DATA "%s" %s %s'''%(filename, timeout, maxDigits) | command = '''GET DATA "%s" %s'''%(filename, timeout) if maxDigits is not None: command = ' '.join([command, str(maxDigits)]) | def getData( self, filename, timeout=2.000, maxDigits=None ): """Playback file, collecting up to maxDigits or waiting up to timeout |
return self.sendDeferred( message ).addCallback( self.errorUnlessResponse, expected = 'Pong', ) | if self.amiVersion == "1.0": return self.sendDeferred(message).addCallback( self.errorUnlessResponse, expected = 'Pong', ) else: return self.sendDeferred(message).addCallback( self.errorUnlessResponse ) | def ping( self ): """Check to see if the manager is alive...""" message = {'action':'ping'} return self.sendDeferred( message ).addCallback( self.errorUnlessResponse, expected = 'Pong', ) |
return self.sendCommand( command ).addCallback( self.checkFailure, ).addCallback( self.onStreamingComplete, skipMS=skipMS ) | return self.sendCommand( command ).addCallback( self.checkFailure ) | def controlStreamFile( self, filename, escapeDigits, skipMS=0, ffChar='*', rewChar='#', pauseChar=None, |
if move.purchase_line_id and move.picking_id.pricelist_id.currency_id: reference_amount, reference_currency_id = move.purchase_line_id.price_unit, move.picking_id.pricelist_id.currency_id.id | if move.sale_line_id and move.picking_id.pricelist_id.currency_id: reference_amount, reference_currency_id = move.sale_line_id.price_unit, move.picking_id.pricelist_id.currency_id.id | def _get_reference_accounting_values_for_valuation(self, cr, uid, move, context=None): """ Overrides the default stock valuation to take into account the currency that was specified on the sale order in case the valuation data was not directly specified during picking confirmation. """ reference_amount, reference_currency_id = super(stock_move, self)._get_reference_accounting_values_for_valuation(cr, uid, move, context=context) if move.product_id.cost_method != 'average' or not move.price_unit: # no average price costing or cost not specified during picking validation, we will # plug the sale line values if they are found. if move.purchase_line_id and move.picking_id.pricelist_id.currency_id: reference_amount, reference_currency_id = move.purchase_line_id.price_unit, move.picking_id.pricelist_id.currency_id.id return reference_amount, reference_currency_id |
context={} for m in move_obj.browse(cr, uid, context.get('active_ids', [])): if m.state in ('done', 'cancel'): | context = {} for move in move_obj.browse(cr, uid, context.get('active_ids', [])): if move.state in ('done', 'cancel'): | def view_init(self, cr, uid, fields_list, context=None): res = super(stock_partial_move, self).view_init(cr, uid, fields_list, context=context) move_obj = self.pool.get('stock.move') if not context: context={} for m in move_obj.browse(cr, uid, context.get('active_ids', [])): if m.state in ('done', 'cancel'): raise osv.except_osv(_('Invalid action !'), _('Cannot deliver products which are already delivered !')) |
if 'move%s_product_id'%(m.id) not in self._columns: self._columns['move%s_product_id'%(m.id)] = fields.many2one('product.product',string="Product") if 'move%s_product_qty'%(m.id) not in self._columns: self._columns['move%s_product_qty'%(m.id)] = fields.float("Quantity") if 'move%s_product_uom'%(m.id) not in self._columns: self._columns['move%s_product_uom'%(m.id)] = fields.many2one('product.uom',string="Product UOM") if 'move%s_prodlot_id'%(m.id) not in self._columns: self._columns['move%s_prodlot_id'%(m.id)] = fields.many2one('stock.production.lot', string="Lot") if (m.picking_id.type == 'in') and (m.product_id.cost_method == 'average'): if 'move%s_product_price'%(m.id) not in self._columns: self._columns['move%s_product_price'%(m.id)] = fields.float("Cost", help="Unit Cost for this product line") if 'move%s_product_currency'%(m.id) not in self._columns: self._columns['move%s_product_currency'%(m.id)] = fields.many2one('res.currency', string="Currency", help="Currency in which Unit cost is expressed") | def __get_active_stock_moves(self, cr, uid, context=None): move_obj = self.pool.get('stock.move') if not context: context = {} res = [] for move in move_obj.browse(cr, uid, context.get('active_ids', [])): if move.state in ('done', 'cancel'): continue res.append(self.__create_partial_move_memory(move)) print res | def view_init(self, cr, uid, fields_list, context=None): res = super(stock_partial_move, self).view_init(cr, uid, fields_list, context=context) move_obj = self.pool.get('stock.move') if not context: context={} for m in move_obj.browse(cr, uid, context.get('active_ids', [])): if m.state in ('done', 'cancel'): raise osv.except_osv(_('Invalid action !'), _('Cannot deliver products which are already delivered !')) |
def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False,submenu=False): print context | def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False): height = 2 * 25; | def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False,submenu=False): print context message = { 'title' : '_(Deliver Products)', 'info' : '_(Delivery Information)', 'button' : '_Deliver' } if context: if context.get('product_receive', False): message = { 'title' : '_(Receive Products)', 'info' : '_(Receive Information)', 'button' : '_Receive' } result = super(stock_partial_move, self).fields_view_get(cr, uid, view_id, view_type, context, toolbar,submenu) move_obj = self.pool.get('stock.move') move_ids = context.get('active_ids', False) move_ids = move_obj.search(cr, uid, [('id','in',move_ids)]) _moves_arch_lst = """<form string="%(title)s"> <separator colspan="4" string="%(info)s"/> <field name="date" colspan="2"/> <separator colspan="4" string="Move Detail"/> """ % message _moves_fields = result['fields'] if move_ids and view_type in ['form']: for m in move_obj.browse(cr, uid, move_ids, context): if m.state in ('done', 'cancel'): continue _moves_fields.update({ 'move%s_product_id'%(m.id) : { 'string': _('Product'), 'type' : 'many2one', 'relation': 'product.product', 'required' : True, 'readonly' : True, }, 'move%s_product_qty'%(m.id) : { 'string': _('Quantity'), 'type' : 'float', 'required': True, }, 'move%s_product_uom'%(m.id) : { 'string': _('Product UOM'), 'type' : 'many2one', 'relation': 'product.uom', 'required' : True, 'readonly' : True, }, 'move%s_prodlot_id'%(m.id): { 'string': _('Production Lot'), 'type': 'many2one', 'relation': 'stock.production.lot', } }) |
'title' : '_(Deliver Products)', 'info' : '_(Delivery Information)', 'button' : '_Deliver' | 'title' : _('Deliver Products'), 'info' : _('Delivery Information'), 'button' : _('Deliver'), | def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False,submenu=False): print context message = { 'title' : '_(Deliver Products)', 'info' : '_(Delivery Information)', 'button' : '_Deliver' } if context: if context.get('product_receive', False): message = { 'title' : '_(Receive Products)', 'info' : '_(Receive Information)', 'button' : '_Receive' } result = super(stock_partial_move, self).fields_view_get(cr, uid, view_id, view_type, context, toolbar,submenu) move_obj = self.pool.get('stock.move') move_ids = context.get('active_ids', False) move_ids = move_obj.search(cr, uid, [('id','in',move_ids)]) _moves_arch_lst = """<form string="%(title)s"> <separator colspan="4" string="%(info)s"/> <field name="date" colspan="2"/> <separator colspan="4" string="Move Detail"/> """ % message _moves_fields = result['fields'] if move_ids and view_type in ['form']: for m in move_obj.browse(cr, uid, move_ids, context): if m.state in ('done', 'cancel'): continue _moves_fields.update({ 'move%s_product_id'%(m.id) : { 'string': _('Product'), 'type' : 'many2one', 'relation': 'product.product', 'required' : True, 'readonly' : True, }, 'move%s_product_qty'%(m.id) : { 'string': _('Quantity'), 'type' : 'float', 'required': True, }, 'move%s_product_uom'%(m.id) : { 'string': _('Product UOM'), 'type' : 'many2one', 'relation': 'product.uom', 'required' : True, 'readonly' : True, }, 'move%s_prodlot_id'%(m.id): { 'string': _('Production Lot'), 'type': 'many2one', 'relation': 'stock.production.lot', } }) |
'title' : '_(Receive Products)', 'info' : '_(Receive Information)', 'button' : '_Receive' | 'title' : _('Receive Products'), 'info' : _('Receive Information'), 'button' : _('Receive'), | def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False,submenu=False): print context message = { 'title' : '_(Deliver Products)', 'info' : '_(Delivery Information)', 'button' : '_Deliver' } if context: if context.get('product_receive', False): message = { 'title' : '_(Receive Products)', 'info' : '_(Receive Information)', 'button' : '_Receive' } result = super(stock_partial_move, self).fields_view_get(cr, uid, view_id, view_type, context, toolbar,submenu) move_obj = self.pool.get('stock.move') move_ids = context.get('active_ids', False) move_ids = move_obj.search(cr, uid, [('id','in',move_ids)]) _moves_arch_lst = """<form string="%(title)s"> <separator colspan="4" string="%(info)s"/> <field name="date" colspan="2"/> <separator colspan="4" string="Move Detail"/> """ % message _moves_fields = result['fields'] if move_ids and view_type in ['form']: for m in move_obj.browse(cr, uid, move_ids, context): if m.state in ('done', 'cancel'): continue _moves_fields.update({ 'move%s_product_id'%(m.id) : { 'string': _('Product'), 'type' : 'many2one', 'relation': 'product.product', 'required' : True, 'readonly' : True, }, 'move%s_product_qty'%(m.id) : { 'string': _('Quantity'), 'type' : 'float', 'required': True, }, 'move%s_product_uom'%(m.id) : { 'string': _('Product UOM'), 'type' : 'many2one', 'relation': 'product.uom', 'required' : True, 'readonly' : True, }, 'move%s_prodlot_id'%(m.id): { 'string': _('Production Lot'), 'type': 'many2one', 'relation': 'stock.production.lot', } }) |
result = super(stock_partial_move, self).fields_view_get(cr, uid, view_id, view_type, context, toolbar,submenu) move_obj = self.pool.get('stock.move') move_ids = context.get('active_ids', False) move_ids = move_obj.search(cr, uid, [('id','in',move_ids)]) _moves_arch_lst = """<form string="%(title)s"> <separator colspan="4" string="%(info)s"/> <field name="date" colspan="2"/> <separator colspan="4" string="Move Detail"/> """ % message | result = super(stock_partial_move, self).fields_view_get(cr, uid, view_id, view_type, context, toolbar, submenu) | def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False,submenu=False): print context message = { 'title' : '_(Deliver Products)', 'info' : '_(Delivery Information)', 'button' : '_Deliver' } if context: if context.get('product_receive', False): message = { 'title' : '_(Receive Products)', 'info' : '_(Receive Information)', 'button' : '_Receive' } result = super(stock_partial_move, self).fields_view_get(cr, uid, view_id, view_type, context, toolbar,submenu) move_obj = self.pool.get('stock.move') move_ids = context.get('active_ids', False) move_ids = move_obj.search(cr, uid, [('id','in',move_ids)]) _moves_arch_lst = """<form string="%(title)s"> <separator colspan="4" string="%(info)s"/> <field name="date" colspan="2"/> <separator colspan="4" string="Move Detail"/> """ % message _moves_fields = result['fields'] if move_ids and view_type in ['form']: for m in move_obj.browse(cr, uid, move_ids, context): if m.state in ('done', 'cancel'): continue _moves_fields.update({ 'move%s_product_id'%(m.id) : { 'string': _('Product'), 'type' : 'many2one', 'relation': 'product.product', 'required' : True, 'readonly' : True, }, 'move%s_product_qty'%(m.id) : { 'string': _('Quantity'), 'type' : 'float', 'required': True, }, 'move%s_product_uom'%(m.id) : { 'string': _('Product UOM'), 'type' : 'many2one', 'relation': 'product.uom', 'required' : True, 'readonly' : True, }, 'move%s_prodlot_id'%(m.id): { 'string': _('Production Lot'), 'type': 'many2one', 'relation': 'stock.production.lot', } }) |
if move_ids and view_type in ['form']: for m in move_obj.browse(cr, uid, move_ids, context): if m.state in ('done', 'cancel'): continue _moves_fields.update({ 'move%s_product_id'%(m.id) : { 'string': _('Product'), 'type' : 'many2one', 'relation': 'product.product', 'required' : True, 'readonly' : True, }, 'move%s_product_qty'%(m.id) : { 'string': _('Quantity'), 'type' : 'float', 'required': True, }, 'move%s_product_uom'%(m.id) : { 'string': _('Product UOM'), 'type' : 'many2one', 'relation': 'product.uom', 'required' : True, 'readonly' : True, }, 'move%s_prodlot_id'%(m.id): { 'string': _('Production Lot'), 'type': 'many2one', 'relation': 'stock.production.lot', } }) _moves_arch_lst += """ <group colspan="4" col="10"> <field name="move%s_product_id" nolabel="1"/> <field name="move%s_product_qty" string="Qty" /> <field name="move%s_product_uom" nolabel="1" /> <field name="move%s_prodlot_id" domain="[('product_id','=',move%s_product_id)]" groups="base.group_extended" /> """%(m.id, m.id, m.id,m.id,m.id) if (m.picking_id.type == 'in') and (m.product_id.cost_method == 'average'): _moves_fields.update({ 'move%s_product_price'%(m.id) : { 'string': _('Cost'), 'type' : 'float', 'help': _('Unit Cost for this product line'), }, 'move%s_product_currency'%(m.id): { 'string': _('Currency'), 'type' : 'many2one', 'relation': 'res.currency', 'help': _("Currency in which Unit Cost is expressed"), } }) _moves_arch_lst += """ <field name="move%s_product_price" /> <field name="move%s_product_currency" nolabel="1"/> """%(m.id, m.id) _moves_arch_lst += """ | _moves_fields.update({'product_moves' : { 'relation': 'stock.move.memory', 'type' : 'one2many', 'string' : 'Product Moves', } }) _moves_arch_lst = """ <form string="%(title)s"> <separator colspan="4" string="%(info)s"/> <field name="date" colspan="2"/> <separator colspan="4" string="Move Detail"/> <field name="product_moves" colspan="4" nolabel="1" width="550" height="200" /> <separator string="" colspan="4" /> <label string="" colspan="2"/> <group col="2" colspan="2"> <button icon='gtk-cancel' special="cancel" string="_Cancel" /> <button name="do_partial" string="%(button)s" colspan="1" type="object" icon="gtk-apply" /> | def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False,submenu=False): print context message = { 'title' : '_(Deliver Products)', 'info' : '_(Delivery Information)', 'button' : '_Deliver' } if context: if context.get('product_receive', False): message = { 'title' : '_(Receive Products)', 'info' : '_(Receive Information)', 'button' : '_Receive' } result = super(stock_partial_move, self).fields_view_get(cr, uid, view_id, view_type, context, toolbar,submenu) move_obj = self.pool.get('stock.move') move_ids = context.get('active_ids', False) move_ids = move_obj.search(cr, uid, [('id','in',move_ids)]) _moves_arch_lst = """<form string="%(title)s"> <separator colspan="4" string="%(info)s"/> <field name="date" colspan="2"/> <separator colspan="4" string="Move Detail"/> """ % message _moves_fields = result['fields'] if move_ids and view_type in ['form']: for m in move_obj.browse(cr, uid, move_ids, context): if m.state in ('done', 'cancel'): continue _moves_fields.update({ 'move%s_product_id'%(m.id) : { 'string': _('Product'), 'type' : 'many2one', 'relation': 'product.product', 'required' : True, 'readonly' : True, }, 'move%s_product_qty'%(m.id) : { 'string': _('Quantity'), 'type' : 'float', 'required': True, }, 'move%s_product_uom'%(m.id) : { 'string': _('Product UOM'), 'type' : 'many2one', 'relation': 'product.uom', 'required' : True, 'readonly' : True, }, 'move%s_prodlot_id'%(m.id): { 'string': _('Production Lot'), 'type': 'many2one', 'relation': 'stock.production.lot', } }) |
<separator string="" colspan="4" /> <label string="" colspan="2"/> <group col="2" colspan="2"> <button icon='gtk-cancel' special="cancel" string="_Cancel" /> <button name="do_partial" string="%(button)s" colspan="1" type="object" icon="gtk-apply" /> </group> </form>""" % message | </form> """ % message | def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False,submenu=False): print context message = { 'title' : '_(Deliver Products)', 'info' : '_(Delivery Information)', 'button' : '_Deliver' } if context: if context.get('product_receive', False): message = { 'title' : '_(Receive Products)', 'info' : '_(Receive Information)', 'button' : '_Receive' } result = super(stock_partial_move, self).fields_view_get(cr, uid, view_id, view_type, context, toolbar,submenu) move_obj = self.pool.get('stock.move') move_ids = context.get('active_ids', False) move_ids = move_obj.search(cr, uid, [('id','in',move_ids)]) _moves_arch_lst = """<form string="%(title)s"> <separator colspan="4" string="%(info)s"/> <field name="date" colspan="2"/> <separator colspan="4" string="Move Detail"/> """ % message _moves_fields = result['fields'] if move_ids and view_type in ['form']: for m in move_obj.browse(cr, uid, move_ids, context): if m.state in ('done', 'cancel'): continue _moves_fields.update({ 'move%s_product_id'%(m.id) : { 'string': _('Product'), 'type' : 'many2one', 'relation': 'product.product', 'required' : True, 'readonly' : True, }, 'move%s_product_qty'%(m.id) : { 'string': _('Quantity'), 'type' : 'float', 'required': True, }, 'move%s_product_uom'%(m.id) : { 'string': _('Product UOM'), 'type' : 'many2one', 'relation': 'product.uom', 'required' : True, 'readonly' : True, }, 'move%s_prodlot_id'%(m.id): { 'string': _('Production Lot'), 'type': 'many2one', 'relation': 'stock.production.lot', } }) |
def default_get(self, cr, uid, fields, context=None): """ To get default values for the object. @param self: The object pointer. @param cr: A database cursor @param uid: ID of the user currently logged in @param fields: List of fields for which we want default values @param context: A standard dictionary @return: A dictionary which of fields with values. """ res = super(stock_partial_move, self).default_get(cr, uid, fields, context=context) move_obj = self.pool.get('stock.move') if not context: context={} if 'date' in fields: res.update({'date': time.strftime('%Y-%m-%d %H:%M:%S')}) move_ids = context.get('active_ids', []) move_ids = move_obj.search(cr, uid, [('id','in',move_ids)]) for m in move_obj.browse(cr, uid, context.get('active_ids', [])): if m.state in ('done', 'cancel'): continue res['type'] = m.picking_id and m.picking_id.type or '' if 'move%s_product_id'%(m.id) in fields: res['move%s_product_id'%(m.id)] = m.product_id.id if 'move%s_product_qty'%(m.id) in fields: res['move%s_product_qty'%(m.id)] = m.product_qty if 'move%s_product_uom'%(m.id) in fields: res['move%s_product_uom'%(m.id)] = m.product_uom.id if 'move%s_prodlot_id'%(m.id) in fields: res['move%s_prodlot_id'%(m.id)] = m.prodlot_id.id if m.picking_id.type == 'in' and m.product_id.cost_method == 'average': currency = m.product_id.company_id.currency_id.id price = m.product_id.standard_price if 'move%s_product_price'%(m.id) in fields: res['move%s_product_price'%(m.id)] = price if 'move%s_product_currency'%(m.id) in fields: res['move%s_product_currency'%(m.id)] = currency return res | def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False,submenu=False): print context message = { 'title' : '_(Deliver Products)', 'info' : '_(Delivery Information)', 'button' : '_Deliver' } if context: if context.get('product_receive', False): message = { 'title' : '_(Receive Products)', 'info' : '_(Receive Information)', 'button' : '_Receive' } result = super(stock_partial_move, self).fields_view_get(cr, uid, view_id, view_type, context, toolbar,submenu) move_obj = self.pool.get('stock.move') move_ids = context.get('active_ids', False) move_ids = move_obj.search(cr, uid, [('id','in',move_ids)]) _moves_arch_lst = """<form string="%(title)s"> <separator colspan="4" string="%(info)s"/> <field name="date" colspan="2"/> <separator colspan="4" string="Move Detail"/> """ % message _moves_fields = result['fields'] if move_ids and view_type in ['form']: for m in move_obj.browse(cr, uid, move_ids, context): if m.state in ('done', 'cancel'): continue _moves_fields.update({ 'move%s_product_id'%(m.id) : { 'string': _('Product'), 'type' : 'many2one', 'relation': 'product.product', 'required' : True, 'readonly' : True, }, 'move%s_product_qty'%(m.id) : { 'string': _('Quantity'), 'type' : 'float', 'required': True, }, 'move%s_product_uom'%(m.id) : { 'string': _('Product UOM'), 'type' : 'many2one', 'relation': 'product.uom', 'required' : True, 'readonly' : True, }, 'move%s_prodlot_id'%(m.id): { 'string': _('Production Lot'), 'type': 'many2one', 'relation': 'stock.production.lot', } }) |
|
for m in move_obj.browse(cr, uid, move_ids): if m.state in ('done', 'cancel'): | p_moves = {} for product_move in partial.product_moves: p_moves[product_move.move_id.id] = product_move moves_ids_final = [] for move in move_obj.browse(cr, uid, move_ids): if move.state in ('done', 'cancel'): | def do_partial(self, cr, uid, ids, context): """ Makes partial moves and pickings done. @param self: The object pointer. @param cr: A database cursor @param uid: ID of the user currently logged in @param fields: List of fields for which we want default values @param context: A standard dictionary @return: A dictionary which of fields with values. """ |
partial_datas['move%s'%(m.id)] = { 'product_id' : getattr(partial, 'move%s_product_id'%(m.id)).id, 'product_qty' : getattr(partial, 'move%s_product_qty'%(m.id)), 'product_uom' : getattr(partial, 'move%s_product_uom'%(m.id)).id, 'prodlot_id' : getattr(partial, 'move%s_prodlot_id'%(m.id)).id | if not p_moves.get(move.id, False): continue partial_datas['move%s' % (move.id)] = { 'product_id' : p_moves[move.id].product_id.id, 'product_qty' : p_moves[move.id].quantity, 'product_uom' : p_moves[move.id].product_uom.id, 'prodlot_id' : p_moves[move.id].prodlot_id.id, | def do_partial(self, cr, uid, ids, context): """ Makes partial moves and pickings done. @param self: The object pointer. @param cr: A database cursor @param uid: ID of the user currently logged in @param fields: List of fields for which we want default values @param context: A standard dictionary @return: A dictionary which of fields with values. """ |
if (m.picking_id.type == 'in') and (m.product_id.cost_method == 'average'): partial_datas['move%s'%(m.id)].update({ 'product_price' : getattr(partial, 'move%s_product_price'%(m.id)), 'product_currency': getattr(partial, 'move%s_product_currency'%(m.id)).id | moves_ids_final.append(move.id) if (move.picking_id.type == 'in') and (move.product_id.cost_method == 'average'): partial_datas['move%s' % (move.id)].update({ 'product_price' : p_moves[move.id].cost, 'product_currency': p_moves[move.id].currency.id, | def do_partial(self, cr, uid, ids, context): """ Makes partial moves and pickings done. @param self: The object pointer. @param cr: A database cursor @param uid: ID of the user currently logged in @param fields: List of fields for which we want default values @param context: A standard dictionary @return: A dictionary which of fields with values. """ |
move_obj.do_partial(cr, uid, move_ids, partial_datas, context=context) | move_obj.do_partial(cr, uid, moves_ids_final, partial_datas, context=context) | def do_partial(self, cr, uid, ids, context): """ Makes partial moves and pickings done. @param self: The object pointer. @param cr: A database cursor @param uid: ID of the user currently logged in @param fields: List of fields for which we want default values @param context: A standard dictionary @return: A dictionary which of fields with values. """ |
stock_partial_move_memory() | def do_partial(self, cr, uid, ids, context): """ Makes partial moves and pickings done. @param self: The object pointer. @param cr: A database cursor @param uid: ID of the user currently logged in @param fields: List of fields for which we want default values @param context: A standard dictionary @return: A dictionary which of fields with values. """ |
|
to_update = self.product_id_change_unit_price_inv(cr, uid, tax_id, price_unit, qty, address_invoice_id, product, partner_id, context=context) | to_update = self.product_id_change_unit_price_inv(cr, uid, tax_id, price_unit or res.standard_price, qty, address_invoice_id, product, partner_id, context=context) | def product_id_change(self, cr, uid, ids, product, uom, qty=0, name='', type='out_invoice', partner_id=False, fposition_id=False, price_unit=False, address_invoice_id=False, context=None): if context is None: context = {} if not partner_id: raise osv.except_osv(_('No Partner Defined !'),_("You must first select a partner !") ) if not product: if type in ('in_invoice', 'in_refund'): return {'domain':{'product_uom':[]}} else: return {'value': {'price_unit': 0.0}, 'domain':{'product_uom':[]}} part = self.pool.get('res.partner').browse(cr, uid, partner_id) fpos = fposition_id and self.pool.get('account.fiscal.position').browse(cr, uid, fposition_id) or False |
'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'resource.resource', c) | 'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'resource.resource', context=c) | def interval_get(self, cr, uid, id, dt_from, hours, resource=False, byday=True): resource_cal_leaves = self.pool.get('resource.calendar.leaves') dt_leave = [] if not id: return [(dt_from,dt_from + mx.DateTime.RelativeDateTime(hours=int(hours)*3))] resource_leave_ids = resource_cal_leaves.search(cr, uid, [('calendar_id','=',id), '|', ('resource_id','=',False), ('resource_id','=',resource)]) res_leaves = resource_cal_leaves.read(cr, uid, resource_leave_ids, ['date_from', 'date_to']) for leave in res_leaves: dtf = mx.DateTime.strptime(leave['date_from'], '%Y-%m-%d %H:%M:%S') dtt = mx.DateTime.strptime(leave['date_to'], '%Y-%m-%d %H:%M:%S') no = dtt - dtf [dt_leave.append((dtf + mx.DateTime.RelativeDateTime(days=x)).strftime('%Y-%m-%d')) for x in range(int(no.days + 1))] dt_leave.sort() todo = hours cycle = 0 result = [] maxrecur = 100 current_hour = dt_from.hour while (todo>0) and maxrecur: cr.execute("select hour_from,hour_to from resource_calendar_week where dayofweek='%s' and calendar_id=%s order by hour_from", (dt_from.day_of_week,id)) for (hour_from,hour_to) in cr.fetchall(): leave_flag = False if (hour_to>current_hour) and (todo>0): m = max(hour_from, current_hour) if (hour_to-m)>todo: hour_to = m+todo dt_check = dt_from.strftime('%Y-%m-%d') for leave in dt_leave: if dt_check == leave: dt_check = mx.DateTime.strptime(dt_check, "%Y-%m-%d") + mx.DateTime.RelativeDateTime(days=1) leave_flag = True if leave_flag: break else: d1 = mx.DateTime.DateTime(dt_from.year, dt_from.month, dt_from.day, int(math.floor(m)), int((m%1) * 60)) d2 = mx.DateTime.DateTime(dt_from.year, dt_from.month, dt_from.day, int(math.floor(hour_to)), int((hour_to%1) * 60)) result.append((d1, d2)) current_hour = hour_to todo -= (hour_to - m) dt_from += mx.DateTime.RelativeDateTime(days=1) current_hour = 0 maxrecur -= 1 return result |
cr.execute('Update crm_meeting set caldav_alarm_id=%s where id=%s' % (alarm_id, meeting.id)) | cr.execute('Update crm_meeting set caldav_alarm_id=%s \ where id=%s' % (alarm_id, meeting.id)) | def do_alarm_create(self, cr, uid, ids, context={}): alarm_obj = self.pool.get('calendar.alarm') model_obj = self.pool.get('ir.model') model_id = model_obj.search(cr, uid, [('model','=',self._name)])[0] |
cr.execute('Update crm_meeting set caldav_alarm_id=NULL where id=%s' % (meeting.id)) | cr.execute('Update crm_meeting set caldav_alarm_id=NULL, \ alarm_id=NULL where id=%s' % (meeting.id)) | def do_alarm_unlink(self, cr, uid, ids, context={}): alarm_obj = self.pool.get('calendar.alarm') model_obj = self.pool.get('ir.model') model_id = model_obj.search(cr, uid, [('model','=',self._name)])[0] for meeting in self.browse(cr, uid, ids): alarm_ids = alarm_obj.search(cr, uid, [('model_id','=',model_id), ('res_id','=',meeting.id)]) if alarm_ids and len(alarm_ids): alarm_obj.unlink(cr, uid, alarm_ids) cr.execute('Update crm_meeting set caldav_alarm_id=NULL where id=%s' % (meeting.id)) cr.commit() return True |
return adr and res_partner_address.read(self.cr, self.uid, [adr]) or False | return adr and res_partner_address.read(self.cr, self.uid, [adr]) or [{}] | def _adr_get(self, partner, type): res_partner = pooler.get_pool(self.cr.dbname).get('res.partner') res_partner_address = pooler.get_pool(self.cr.dbname).get('res.partner.address') adr = res_partner.address_get(self.cr, self.uid, [partner.id], [type])[type] return adr and res_partner_address.read(self.cr, self.uid, [adr]) or False |
if uom.factor: res[uom.id] = round(1 / uom.factor, 6) else: res[uom.id] = 0.0 | res[uom.id] = self._compute_factor_inv(uom.factor) | def _factor_inv(self, cursor, user, ids, name, arg, context): res = {} for uom in self.browse(cursor, user, ids, context=context): if uom.factor: res[uom.id] = round(1 / uom.factor, 6) else: res[uom.id] = 0.0 return res |
if value: self.write(cursor, user, id, { 'factor': round(1/value, 6), }, context=context) else: self.write(cursor, user, id, { 'factor': 0.0, }, context=context) return True | return self.write(cursor, user, id, {'factor': self._compute_factor_inv(value)}, context=context) def create(self, cr, uid, data, context={}): if 'factor_inv' in data: if data['factor_inv'] <> 1: data['factor'] = self._compute_factor_inv(data['factor_inv']) del(data['factor_inv']) return super(product_uom, self).create(cr, uid, data, context) | def _factor_inv_write(self, cursor, user, id, name, value, arg, context): if value: self.write(cursor, user, id, { 'factor': round(1/value, 6), }, context=context) else: self.write(cursor, user, id, { 'factor': 0.0, }, context=context) return True |
('reference','Reference UoM for this category (ratio=1)'), | ('reference','Reference UoM for this category'), | def _factor_inv_write(self, cursor, user, id, name, value, arg, context): if value: self.write(cursor, user, id, { 'factor': round(1/value, 6), }, context=context) else: self.write(cursor, user, id, { 'factor': 0.0, }, context=context) return True |
'factor': 1.0, 'factor_inv': 1.0, | def _factor_inv_write(self, cursor, user, id, name, value, arg, context): if value: self.write(cursor, user, id, { 'factor': round(1/value, 6), }, context=context) else: self.write(cursor, user, id, { 'factor': 0.0, }, context=context) return True |
|
'account_id': account, | 'account_id': result.get('account_id', statement.journal_id.default_credit_account_id.id), | def populate_statement(self, cr, uid, ids, context=None): line_obj = self.pool.get('payment.line') statement_obj = self.pool.get('account.bank.statement') statement_line_obj = self.pool.get('account.bank.statement.line') currency_obj = self.pool.get('res.currency') voucher_obj = self.pool.get('account.voucher') voucher_line_obj = self.pool.get('account.voucher.line') |
context.update({'move_line_ids': [line.move_line_id.id]}) result = voucher_obj.onchange_partner_id(cr, uid, [], partner_id=line.partner_id.id, journal_id=statement.journal_id.id, price=abs(amount), currency_id= statement.currency.id, ttype='payment', context=context) | def populate_statement(self, cr, uid, ids, context=None): line_obj = self.pool.get('payment.line') statement_obj = self.pool.get('account.bank.statement') statement_line_obj = self.pool.get('account.bank.statement.line') currency_obj = self.pool.get('res.currency') voucher_obj = self.pool.get('account.voucher') voucher_line_obj = self.pool.get('account.voucher.line') |
|
'company_id': lambda self,cr,uid,c: self.pool.get('res.users').browse(cr, uid, uid, c).company_id.id, | 'company_id': _default_company, | def _default_company(self, cr, uid, context={}): """ To get default company for the object" @param self: The object pointer @param cr: the current row, from the database cursor, @param uid: the current user’s ID for security checks, @param ids: List of bank statement ids @param context: A standard dictionary for contextual values @return: company """ user = self.pool.get('res.users').browse(cr, uid, uid, context=context) if user.company_id: return user.company_id.id return self.pool.get('res.company').search(cr, uid, [('parent_id', '=', False)])[0] |
inv_amount_company_currency=invoice.move_id.amount | inv_amount_company_currency = 0.0 for aml in invoice.move_id.line_id: if aml.account_id.id == invoice.account_id.id or aml.account_id.type in ('receivable', 'payable'): inv_amount_company_currency += aml.debit inv_amount_company_currency -= aml.credit inv_amount_company_currency = abs(inv_amount_company_currency) | def _wo_check(self, cr, uid, data, context): pool = pooler.get_pool(cr.dbname) invoice = pool.get('account.invoice').browse(cr, uid, data['id'], context) journal = pool.get('account.journal').browse(cr, uid, data['form']['journal_id'], context) cur_obj = pool.get('res.currency') # Here we need that: # The invoice total amount in company's currency <> paid amount in company currency # (according to the correct day rate, invoicing rate and payment rate are may be different) # => Ask to a write-off of the difference. This could happen even if both amount are equal, # because if the currency rate # Get the amount in company currency for the invoice (according to move lines) inv_amount_company_currency=invoice.move_id.amount # Get the current amount paid in company currency if journal.currency and invoice.company_id.currency_id.id<>journal.currency.id: ctx = {'date':data['form']['date']} amount_paid = cur_obj.compute(cr, uid, journal.currency.id, invoice.company_id.currency_id.id, data['form']['amount'], round=True, context=ctx) else: amount_paid = data['form']['amount'] # Get the old payment if there are some if invoice.payment_ids: debit=credit=0.0 for payment in invoice.payment_ids: debit+=payment.debit credit+=payment.credit amount_paid+=abs(debit-credit) # Test if there is a difference according to currency rouding setting if pool.get('res.currency').is_zero(cr, uid, invoice.company_id.currency_id, (amount_paid - inv_amount_company_currency)): return 'reconcile' return 'addendum' |
'member_ids': fields.one2many('hr.employee', 'department_id', 'Members'), | 'member_ids': fields.one2many('hr.employee', 'department_id', 'Members', readonly=True), | def _check_department_id(self, cr, uid, ids, context=None): for emp in self.browse(cr, uid, ids, context=context): if emp.department_id.manager_id and emp.id == emp.department_id.manager_id.id: return False return True |
"SELECT id, name FROM mrp_workcenter " \ "WHERE id=ANY(%s)" \ "ORDER BY mrp_workcenter.id" ,(ids,)) | "SELECT mw.id, rs.name FROM mrp_workcenter mw, resource_resource rs " \ "WHERE mw.id=ANY(%s) and mw.resource_id=rs.id " \ "ORDER BY mw.id" ,(ids,)) | def create(self, cr, uid, ids, datas, context={}): assert len(ids), 'You should provide some ids!' colors = choice_colors(len(ids)) cr.execute( "SELECT MAX(mrp_production.date_planned) AS stop,MIN(mrp_production.date_planned) AS start "\ "FROM mrp_workcenter, mrp_production, mrp_production_workcenter_line "\ "WHERE mrp_production_workcenter_line.production_id=mrp_production.id "\ "AND mrp_production_workcenter_line.workcenter_id=mrp_workcenter.id "\ "AND mrp_production.state NOT IN ('cancel','done') "\ "AND mrp_workcenter.id =ANY(%s)",(ids,)) res = cr.dictfetchone() if not res['stop']: res['stop'] = time.strftime('%Y-%m-%d %H:%M:%S') if not res['start']: res['start'] = time.strftime('%Y-%m-%d %H:%M:%S') dates = self._compute_dates(datas['form']['time_unit'], res['start'][:10], res['stop'][:10]) dates_list = dates.keys() dates_list.sort() x_index = [] for date in dates_list: x_index.append((dates[date]['name'], date)) pdf_string = StringIO.StringIO() can = canvas.init(fname=pdf_string, format='pdf') chart_object.set_defaults(line_plot.T, line_style=None) if datas['form']['measure_unit'] == 'cycles': y_label = "Load (Cycles)" else: y_label = "Load (Hours)" ar = area.T(legend = legend.T(), x_grid_style = line_style.gray70_dash1, x_axis = axis.X(label="Periods", format="/a90/hC%s"), x_coord = category_coord.T(x_index, 0), y_axis = axis.Y(label=y_label), y_range = (0, None), size = (640,480)) bar_plot.fill_styles.reset(); |
mrp_workcenter.name AS name, mrp_workcenter.id AS id \ FROM mrp_production_workcenter_line, mrp_production, mrp_workcenter \ | resource_resource.name AS name, mrp_workcenter.id AS id \ FROM mrp_production_workcenter_line, mrp_production, mrp_workcenter, resource_resource \ | def create(self, cr, uid, ids, datas, context={}): assert len(ids), 'You should provide some ids!' colors = choice_colors(len(ids)) cr.execute( "SELECT MAX(mrp_production.date_planned) AS stop,MIN(mrp_production.date_planned) AS start "\ "FROM mrp_workcenter, mrp_production, mrp_production_workcenter_line "\ "WHERE mrp_production_workcenter_line.production_id=mrp_production.id "\ "AND mrp_production_workcenter_line.workcenter_id=mrp_workcenter.id "\ "AND mrp_production.state NOT IN ('cancel','done') "\ "AND mrp_workcenter.id =ANY(%s)",(ids,)) res = cr.dictfetchone() if not res['stop']: res['stop'] = time.strftime('%Y-%m-%d %H:%M:%S') if not res['start']: res['start'] = time.strftime('%Y-%m-%d %H:%M:%S') dates = self._compute_dates(datas['form']['time_unit'], res['start'][:10], res['stop'][:10]) dates_list = dates.keys() dates_list.sort() x_index = [] for date in dates_list: x_index.append((dates[date]['name'], date)) pdf_string = StringIO.StringIO() can = canvas.init(fname=pdf_string, format='pdf') chart_object.set_defaults(line_plot.T, line_style=None) if datas['form']['measure_unit'] == 'cycles': y_label = "Load (Cycles)" else: y_label = "Load (Hours)" ar = area.T(legend = legend.T(), x_grid_style = line_style.gray70_dash1, x_axis = axis.X(label="Periods", format="/a90/hC%s"), x_coord = category_coord.T(x_index, 0), y_axis = axis.Y(label=y_label), y_range = (0, None), size = (640,480)) bar_plot.fill_styles.reset(); |
GROUP BY mrp_production_workcenter_line.workcenter_id, mrp_workcenter.name, mrp_workcenter.id \ | GROUP BY mrp_production_workcenter_line.workcenter_id, resource_resource.name, mrp_workcenter.id \ | def create(self, cr, uid, ids, datas, context={}): assert len(ids), 'You should provide some ids!' colors = choice_colors(len(ids)) cr.execute( "SELECT MAX(mrp_production.date_planned) AS stop,MIN(mrp_production.date_planned) AS start "\ "FROM mrp_workcenter, mrp_production, mrp_production_workcenter_line "\ "WHERE mrp_production_workcenter_line.production_id=mrp_production.id "\ "AND mrp_production_workcenter_line.workcenter_id=mrp_workcenter.id "\ "AND mrp_production.state NOT IN ('cancel','done') "\ "AND mrp_workcenter.id =ANY(%s)",(ids,)) res = cr.dictfetchone() if not res['stop']: res['stop'] = time.strftime('%Y-%m-%d %H:%M:%S') if not res['start']: res['start'] = time.strftime('%Y-%m-%d %H:%M:%S') dates = self._compute_dates(datas['form']['time_unit'], res['start'][:10], res['stop'][:10]) dates_list = dates.keys() dates_list.sort() x_index = [] for date in dates_list: x_index.append((dates[date]['name'], date)) pdf_string = StringIO.StringIO() can = canvas.init(fname=pdf_string, format='pdf') chart_object.set_defaults(line_plot.T, line_style=None) if datas['form']['measure_unit'] == 'cycles': y_label = "Load (Cycles)" else: y_label = "Load (Hours)" ar = area.T(legend = legend.T(), x_grid_style = line_style.gray70_dash1, x_axis = axis.X(label="Periods", format="/a90/hC%s"), x_coord = category_coord.T(x_index, 0), y_axis = axis.Y(label=y_label), y_range = (0, None), size = (640,480)) bar_plot.fill_styles.reset(); |
elif action.trg_state_to: ok = False | def do_check(self, cr, uid, action, obj, context={}): """ check Action @param self: The object pointer @param cr: the current row, from the database cursor, @param uid: the current user’s ID for security checks, @param context: A standard dictionary for contextual values """ |
|
if part.property_payment_term and part.property_payment_term.line_ids: payterm = part.property_payment_term.line_ids[0] res = self.pool.get('account.payment.term').compute(cr, uid, payterm.id, 100, date) | if part.property_payment_term: res = self.pool.get('account.payment.term').compute(cr, uid, part.property_payment_term.id, 100, date) | def onchange_partner_id(self, cr, uid, ids, move_id, partner_id, account_id=None, debit=0, credit=0, date=False, journal=False): val = {} val['date_maturity'] = False |
country1 = '' | country = '' | def execute(self, cr, uid, ids, context=None): company_id = self.pool.get('base.setup.company').search(cr, uid, []) company_data = self.pool.get('base.setup.company').read(cr, uid, company_id) company_data = company_data and company_data[0] or False country1 = '' if company_data and company_data.get('country_id', False): country = self.pool.get('res.country').read(cr, uid, company_data['country_id'],['name'])['name'] for res in self.read(cr, uid, ids): email = res.get('email','') result = "\ncompany: "+ str(company_data.get('name','')) result += "\nname: " + str(res.get('name','')) result += "\njob: " + str(res.get('job','')) result += "\nphone: " + str(res.get('phone','')) result += "\ncity: " + str(company_data.get('city','')) result += "\ncountry: " + str(country) result += "\nindustry: " + str(res.get('industry', '')) result += "\ntotal_employees: " + str(res.get('total_employees', '')) result += "\nplan_use: " + str(res.get('use_openerp', False)) result += "\nalready_using_openerp: " + str(res.get('already_using_openerp', False)) result += "\nsell_openerp: " + str(res.get('sell_openerp', False)) result += "\nalready_selling__openerp: " + str(res.get('already_selling__openerp', False)) result += "\nfeatures: " + str(res.get('features', False)) result += "\nsaas: " + str(res.get('saas', False)) result += "\npartners_program: " + str(res.get('partners_program', False)) result += "\nsupport: " + str(res.get('support', False)) result += "\ntraining: " + str(res.get('training', False)) result += "\nupdates: " + str(res.get('updates', False)) result += "\ncontact_me: " + str(res.get('contact_me', False)) result += "\nebook: " + str(res.get('ebook',False)) result += "\ngtk: " + str(True) misc.upload_data(email, result, type='SURVEY') |
def get_data(self, form): | def get_data(self, data): | def get_data(self, form): cr, uid = self.cr, self.uid db_pool = pooler.get_pool(self.cr.dbname) |
ctx['fiscalyear'] = form['fiscalyear'] | ctx['fiscalyear'] = data['form']['fiscalyear_id'] | def get_data(self, form): cr, uid = self.cr, self.uid db_pool = pooler.get_pool(self.cr.dbname) |
if form['filter']=='filter_period' : ctx['periods'] = form['periods'] elif form['filter']== 'filter_date': ctx['date_from'] = form['date_from'] ctx['date_to'] = form['date_to'] | if data['form']['filter']=='filter_period' : ctx['periods'] = data['periods'] elif data['form']['filter']== 'filter_date': ctx['date_from'] = data['date_from'] ctx['date_to'] = data['date_to'] | def get_data(self, form): cr, uid = self.cr, self.uid db_pool = pooler.get_pool(self.cr.dbname) |
account_id = [form['Account_list']] | account_id =data['form']['chart_account_id'] | def get_data(self, form): cr, uid = self.cr, self.uid db_pool = pooler.get_pool(self.cr.dbname) |
if form['display_account'] == 'bal_mouvement': | if data['form']['display_account'] == 'bal_mouvement': | def get_data(self, form): cr, uid = self.cr, self.uid db_pool = pooler.get_pool(self.cr.dbname) |
elif form['display_account'] == 'bal_solde': | elif data['form']['display_account'] == 'bal_solde': | def get_data(self, form): cr, uid = self.cr, self.uid db_pool = pooler.get_pool(self.cr.dbname) |
FROM account_move_line AS line \ | FROM account_move_line AS line, \ account_move AS move \ | def _sum(self, cr, uid, ids, name, args, context,where ='', where_params=()): parent_ids = tuple(self.search(cr, uid, [('parent_id', 'child_of', ids)])) if context.get('based_on', 'invoices') == 'payments': cr.execute('SELECT line.tax_code_id, sum(line.tax_amount) \ FROM account_move_line AS line, \ account_move AS move \ LEFT JOIN account_invoice invoice ON \ (invoice.move_id = move.id) \ WHERE line.tax_code_id IN %s '+where+' \ AND move.id = line.move_id \ AND ((invoice.state = \'paid\') \ OR (invoice.id IS NULL)) \ GROUP BY line.tax_code_id', (parent_ids,)+where_params) else: cr.execute('SELECT line.tax_code_id, sum(line.tax_amount) \ FROM account_move_line AS line \ WHERE line.tax_code_id IN %s '+where+' \ GROUP BY line.tax_code_id', (parent_ids,)+where_params) res=dict(cr.fetchall()) for record in self.browse(cr, uid, ids, context): def _rec_get(record): amount = res.get(record.id, 0.0) for rec in record.child_ids: amount += _rec_get(rec) * rec.sign return amount res[record.id] = round(_rec_get(record), self.pool.get('decimal.precision').precision_get(cr, uid, 'Account')) return res |
def _sum_year(self, cr, uid, ids, name, args, context): | def _sum_year(self, cr, uid, ids, name, args, context=None): if context is None: context = {} move_state = ('posted', ) if 'state' in context and context['state'] == 'all': move_state = ('draft', 'posted', ) | def _sum_year(self, cr, uid, ids, name, args, context): if 'fiscalyear_id' in context and context['fiscalyear_id']: fiscalyear_id = context['fiscalyear_id'] else: fiscalyear_id = self.pool.get('account.fiscalyear').find(cr, uid, exception=False) where = '' where_params = () if fiscalyear_id: pids = map(lambda x: str(x.id), self.pool.get('account.fiscalyear').browse(cr, uid, fiscalyear_id).period_ids) if pids: where = ' and period_id IN %s' where_params = (tuple(pids),) return self._sum(cr, uid, ids, name, args, context, where=where, where_params=where_params) |
where = ' and period_id IN %s' where_params = (tuple(pids),) | where = ' AND line.period_id IN %s AND move.state IN %s ' where_params = (tuple(pids), move_state) | def _sum_year(self, cr, uid, ids, name, args, context): if 'fiscalyear_id' in context and context['fiscalyear_id']: fiscalyear_id = context['fiscalyear_id'] else: fiscalyear_id = self.pool.get('account.fiscalyear').find(cr, uid, exception=False) where = '' where_params = () if fiscalyear_id: pids = map(lambda x: str(x.id), self.pool.get('account.fiscalyear').browse(cr, uid, fiscalyear_id).period_ids) if pids: where = ' and period_id IN %s' where_params = (tuple(pids),) return self._sum(cr, uid, ids, name, args, context, where=where, where_params=where_params) |
where=' and line.period_id=%s', where_params=(period_id,)) | where=' AND line.period_id=%s AND move.state IN %s', where_params=(period_id, move_state)) | def _sum_period(self, cr, uid, ids, name, args, context): if 'period_id' in context and context['period_id']: period_id = context['period_id'] else: period_id = self.pool.get('account.period').find(cr, uid) if not len(period_id): return dict.fromkeys(ids, 0.0) period_id = period_id[0] return self._sum(cr, uid, ids, name, args, context, where=' and line.period_id=%s', where_params=(period_id,)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.