<commit_before># Copyright (c) 2009 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

{
  'includes': [
    '../../build/common.gypi',
  ],
  'target_defaults': {
    'conditions': [
      ['OS!="linux"', {'sources/': [['exclude', '/linux/']]}],
      ['OS!="mac"', {'sources/': [['exclude', '/mac/']]}],
      ['OS!="win"', {'sources/': [['exclude', '/win/']]}],
    ],
  },
  'targets': [
    {
      'variables': {
        'generate_stubs_script': 'generate_stubs.py',
        'sig_files': [
          'avcodec-52.sigs',
          'avformat-52.sigs',
          'avutil-50.sigs',
        ],
        'extra_header': 'ffmpeg_stub_headers.fragment',
      },
      'target_name': 'ffmpeg',
      'msvs_guid': 'D7A94F58-576A-45D9-A45F-EB87C63ABBB0',
      'dependencies': [
        'ffmpeg_binaries',
      ],
      'sources': [
        'include/libavcodec/avcodec.h',
        'include/libavcodec/opt.h',
        'include/libavcodec/vdpau.h',
        'include/libavcodec/xvmc.h',
        'include/libavformat/avformat.h',
        'include/libavformat/avio.h',
        'include/libavutil/adler32.h',
        'include/libavutil/avstring.h',
        'include/libavutil/avutil.h',
        'include/libavutil/base64.h',
        'include/libavutil/common.h',
        'include/libavutil/crc.h',
        'include/libavutil/fifo.h',
        'include/libavutil/intfloat_readwrite.h',
        'include/libavutil/log.h',
        'include/libavutil/lzo.h',
        'include/libavutil/mathematics.h',
        'include/libavutil/md5.h',
        'include/libavutil/mem.h',
        'include/libavutil/pixfmt.h',
        'include/libavutil/rational.h',
        'include/libavutil/sha1.h',
        'include/win/inttypes.h',
        'include/win/stdint.h',
        '<@(sig_files)',
        '<(extra_header)'
      ],
      'hard_dependency': 1,
      'direct_dependent_settings': {
        'include_dirs': [
          'include',
        ],
      },
      'conditions': [
        ['OS=="win"',
          {
            'variables': {
              'outfile_type': 'windows_lib',
              'output_dir': '<(PRODUCT_DIR)/lib',
              'intermediate_dir': '<(INTERMEDIATE_DIR)',
            },
            'type': 'none',
            'sources!': [
              '<(extra_header)',
            ],
            'direct_dependent_settings': {
              'include_dirs': [
                'include/win',
              ],
              'link_settings': {
                'libraries': [
                  '<(output_dir)/avcodec-52.lib',
                  '<(output_dir)/avformat-52.lib',
                  '<(output_dir)/avutil-50.lib',
                ],
                'msvs_settings': {
                  'VCLinkerTool': {
                    'DelayLoadDLLs': [
                      'avcodec-52.dll',
                      'avformat-52.dll',
                      'avutil-50.dll',
                    ],
                  },
                },
              },
            },
            'rules': [
              {
                'rule_name': 'generate_libs',
                'extension': 'sigs',
                'inputs': [
                  '<(generate_stubs_script)',
                  '<@(sig_files)',
                ],
                'outputs': [
                  '<(output_dir)/<(RULE_INPUT_ROOT).lib',
                ],
                'action': ['python', '<(generate_stubs_script)',
                           '-i', '<(intermediate_dir)',
                           '-o', '<(output_dir)',
                           '-t', '<(outfile_type)',
                           '<@(RULE_INPUT_PATH)',
                ],
                'message': 'Generating FFmpeg import libraries.',
              },
            ],
          }, {  # else OS!="win"
            'variables': {
              'outfile_type': 'posix_stubs',
              'stubs_filename_root': 'ffmpeg_stubs',
              'project_path': 'third_party/ffmpeg',
              'intermediate_dir': '<(INTERMEDIATE_DIR)',
              'output_root': '<(SHARED_INTERMEDIATE_DIR)/ffmpeg',
            },
            'type': '<(library)',
            'include_dirs': [
              'include',
              '<(output_root)',
              '../..',  # The chromium 'src' directory.
            ],
            'direct_dependent_settings': {
              'defines': [
                '__STDC_CONSTANT_MACROS',  # FFmpeg uses INT64_C.
              ],
              'include_dirs': [
                '<(output_root)',
                '../..',  # The chromium 'src' directory.
              ],
            },
            'actions': [
              {
                'action_name': 'generate_stubs',
                'inputs': [
                  '<(generate_stubs_script)',
                  '<(extra_header)',
                  '<@(sig_files)',
                ],
                'outputs': [
                  '<(intermediate_dir)/<(stubs_filename_root).cc',
                  '<(output_root)/<(project_path)/<(stubs_filename_root).h',
                ],
                'action': ['python',
                           '<(generate_stubs_script)',
                           '-i', '<(intermediate_dir)',
                           '-o', '<(output_root)/<(project_path)',
                           '-t', '<(outfile_type)',
                           '-e', '<(extra_header)',
                           '-s', '<(stubs_filename_root)',
                           '-p', '<(project_path)',
                           '<@(_inputs)',
                ],
                'message': 'Generating FFmpeg stubs for dynamic loading.',
                'process_outputs_as_sources': 1,
              },
            ],
          }
        ],
      ],
    },
    {
      'target_name': 'ffmpeg_binaries',
      'type': 'none',
      'msvs_guid': '4E4070E1-EFD9-4EF1-8634-3960956F6F10',
      'variables': {
        'conditions': [
          [ 'branding=="Chrome"', {
               'branding_dir': 'chrome',
          }, { # else branding!="Chrome"
               'branding_dir': 'chromium',
          }],
        ],
      },
      'conditions': [
        ['OS=="win"', {
          'variables': {
            'source_files': [
              'binaries/<(branding_dir)/avcodec-52.dll',
              'binaries/<(branding_dir)/avformat-52.dll',
              'binaries/<(branding_dir)/avutil-50.dll',
              'binaries/<(branding_dir)/pthreadGC2.dll',
            ],
          },
          'dependencies': ['../../build/win/system.gyp:cygwin'],
        }], ['OS=="linux"', {
          'variables': {
            'source_files': [
              'binaries/<(branding_dir)/libavcodec.so.52',
              'binaries/<(branding_dir)/libavformat.so.52',
              'binaries/<(branding_dir)/libavutil.so.50',
            ],
          },
        }], ['OS=="mac"', {
              'variables': {
                'source_files': [
                  'binaries/<(branding_dir)/libavcodec.52.dylib',
                  'binaries/<(branding_dir)/libavformat.52.dylib',
                  'binaries/<(branding_dir)/libavutil.50.dylib',
                ],
              },
        }],
      ],
      'copies': [
        {
          'destination': '<(PRODUCT_DIR)/',
          'files': [
            '<@(source_files)',
          ]
        },
      ],
    },
  ],
}
<commit_msg>Linux: add use_system_ffmpeg GYP variable.<commit_after># Copyright (c) 2009 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

{
  'includes': [
    '../../build/common.gypi',
  ],
  'target_defaults': {
    'conditions': [
      ['OS!="linux"', {'sources/': [['exclude', '/linux/']]}],
      ['OS!="mac"', {'sources/': [['exclude', '/mac/']]}],
      ['OS!="win"', {'sources/': [['exclude', '/win/']]}],
    ],
  },
  'variables': {
    'use_system_ffmpeg%': 0,
  },
  'targets': [
    {
      'variables': {
        'generate_stubs_script': 'generate_stubs.py',
        'sig_files': [
          'avcodec-52.sigs',
          'avformat-52.sigs',
          'avutil-50.sigs',
        ],
        'extra_header': 'ffmpeg_stub_headers.fragment',
      },
      'target_name': 'ffmpeg',
      'msvs_guid': 'D7A94F58-576A-45D9-A45F-EB87C63ABBB0',
      'dependencies': [
        'ffmpeg_binaries',
      ],
      'sources': [
        'include/libavcodec/avcodec.h',
        'include/libavcodec/opt.h',
        'include/libavcodec/vdpau.h',
        'include/libavcodec/xvmc.h',
        'include/libavformat/avformat.h',
        'include/libavformat/avio.h',
        'include/libavutil/adler32.h',
        'include/libavutil/avstring.h',
        'include/libavutil/avutil.h',
        'include/libavutil/base64.h',
        'include/libavutil/common.h',
        'include/libavutil/crc.h',
        'include/libavutil/fifo.h',
        'include/libavutil/intfloat_readwrite.h',
        'include/libavutil/log.h',
        'include/libavutil/lzo.h',
        'include/libavutil/mathematics.h',
        'include/libavutil/md5.h',
        'include/libavutil/mem.h',
        'include/libavutil/pixfmt.h',
        'include/libavutil/rational.h',
        'include/libavutil/sha1.h',
        'include/win/inttypes.h',
        'include/win/stdint.h',
        '<@(sig_files)',
        '<(extra_header)'
      ],
      'hard_dependency': 1,
      'direct_dependent_settings': {
        'include_dirs': [
          'include',
        ],
      },
      'conditions': [
        ['OS=="win"',
          {
            'variables': {
              'outfile_type': 'windows_lib',
              'output_dir': '<(PRODUCT_DIR)/lib',
              'intermediate_dir': '<(INTERMEDIATE_DIR)',
            },
            'type': 'none',
            'sources!': [
              '<(extra_header)',
            ],
            'direct_dependent_settings': {
              'include_dirs': [
                'include/win',
              ],
              'link_settings': {
                'libraries': [
                  '<(output_dir)/avcodec-52.lib',
                  '<(output_dir)/avformat-52.lib',
                  '<(output_dir)/avutil-50.lib',
                ],
                'msvs_settings': {
                  'VCLinkerTool': {
                    'DelayLoadDLLs': [
                      'avcodec-52.dll',
                      'avformat-52.dll',
                      'avutil-50.dll',
                    ],
                  },
                },
              },
            },
            'rules': [
              {
                'rule_name': 'generate_libs',
                'extension': 'sigs',
                'inputs': [
                  '<(generate_stubs_script)',
                  '<@(sig_files)',
                ],
                'outputs': [
                  '<(output_dir)/<(RULE_INPUT_ROOT).lib',
                ],
                'action': ['python', '<(generate_stubs_script)',
                           '-i', '<(intermediate_dir)',
                           '-o', '<(output_dir)',
                           '-t', '<(outfile_type)',
                           '<@(RULE_INPUT_PATH)',
                ],
                'message': 'Generating FFmpeg import libraries.',
              },
            ],
          }, {  # else OS!="win"
            'variables': {
              'outfile_type': 'posix_stubs',
              'stubs_filename_root': 'ffmpeg_stubs',
              'project_path': 'third_party/ffmpeg',
              'intermediate_dir': '<(INTERMEDIATE_DIR)',
              'output_root': '<(SHARED_INTERMEDIATE_DIR)/ffmpeg',
            },
            'type': '<(library)',
            'include_dirs': [
              'include',
              '<(output_root)',
              '../..',  # The chromium 'src' directory.
            ],
            'direct_dependent_settings': {
              'defines': [
                '__STDC_CONSTANT_MACROS',  # FFmpeg uses INT64_C.
              ],
              'include_dirs': [
                '<(output_root)',
                '../..',  # The chromium 'src' directory.
              ],
            },
            'actions': [
              {
                'action_name': 'generate_stubs',
                'inputs': [
                  '<(generate_stubs_script)',
                  '<(extra_header)',
                  '<@(sig_files)',
                ],
                'outputs': [
                  '<(intermediate_dir)/<(stubs_filename_root).cc',
                  '<(output_root)/<(project_path)/<(stubs_filename_root).h',
                ],
                'action': ['python',
                           '<(generate_stubs_script)',
                           '-i', '<(intermediate_dir)',
                           '-o', '<(output_root)/<(project_path)',
                           '-t', '<(outfile_type)',
                           '-e', '<(extra_header)',
                           '-s', '<(stubs_filename_root)',
                           '-p', '<(project_path)',
                           '<@(_inputs)',
                ],
                'message': 'Generating FFmpeg stubs for dynamic loading.',
                'process_outputs_as_sources': 1,
              },
            ],
          }
        ],
      ],
    },
    {
      'target_name': 'ffmpeg_binaries',
      'type': 'none',
      'msvs_guid': '4E4070E1-EFD9-4EF1-8634-3960956F6F10',
      'variables': {
        'conditions': [
          [ 'branding=="Chrome"', {
               'branding_dir': 'chrome',
          }, { # else branding!="Chrome"
               'branding_dir': 'chromium',
          }],
        ],
      },
      'conditions': [
        ['OS=="win"', {
          'variables': {
            'source_files': [
              'binaries/<(branding_dir)/avcodec-52.dll',
              'binaries/<(branding_dir)/avformat-52.dll',
              'binaries/<(branding_dir)/avutil-50.dll',
              'binaries/<(branding_dir)/pthreadGC2.dll',
            ],
          },
          'dependencies': ['../../build/win/system.gyp:cygwin'],
        }], ['OS=="linux"', {
          'conditions': [
            ['use_system_ffmpeg==0', {
              'variables': {
                'source_files': [
                  'binaries/<(branding_dir)/libavcodec.so.52',
                  'binaries/<(branding_dir)/libavformat.so.52',
                  'binaries/<(branding_dir)/libavutil.so.50',
                ],
              },
            }, {
              'variables': {
                'source_files': []
              },
            }],
          ]},
        ], ['OS=="mac"', {
              'variables': {
                'source_files': [
                  'binaries/<(branding_dir)/libavcodec.52.dylib',
                  'binaries/<(branding_dir)/libavformat.52.dylib',
                  'binaries/<(branding_dir)/libavutil.50.dylib',
                ],
              },
        }],
      ],
      'copies': [
        {
          'destination': '<(PRODUCT_DIR)/',
          'files': [
            '<@(source_files)',
          ]
        },
      ],
    },
  ],
}
<|endoftext|>


<commit_before># Copyright (c) 2009 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

{
  'variables': {
    'conditions': [
      ['OS=="linux" or OS=="freebsd" or OS=="openbsd" or OS=="solaris"', {
        'os_include': 'linux'
      }],
      ['OS=="mac"', {'os_include': 'mac'}],
      ['OS=="win"', {'os_include': 'win32'}],
    ],
    'use_system_libxml%': 0,
  },
  'targets': [
    {
      'target_name': 'libxml',
      'conditions': [
        ['(OS=="linux" or OS=="freebsd" or OS=="openbsd" or OS=="solaris") and use_system_libxml', {
          'type': 'settings',
          'direct_dependent_settings': {
            'cflags': [
              '<!@(pkg-config --cflags libxml-2.0)',
            ],
            'defines': [
              'USE_SYSTEM_LIBXML',
            ],
          },
          'link_settings': {
            'ldflags': [
              '<!@(pkg-config --libs-only-L --libs-only-other libxml-2.0)',
            ],
            'libraries': [
              '<!@(pkg-config --libs-only-l libxml-2.0)',
            ],
          },
        }, { # else: OS != "linux" or ! use_system_libxml
          'type': '<(library)',
          'msvs_guid': 'F9810DE8-CBC3-4605-A7B1-ECA2D5292FD7',
          'sources': [
            'include/libxml/c14n.h',
            'include/libxml/catalog.h',
            'include/libxml/chvalid.h',
            'include/libxml/debugXML.h',
            'include/libxml/dict.h',
            'include/libxml/DOCBparser.h',
            'include/libxml/encoding.h',
            'include/libxml/entities.h',
            'include/libxml/globals.h',
            'include/libxml/hash.h',
            'include/libxml/HTMLparser.h',
            'include/libxml/HTMLtree.h',
            'include/libxml/list.h',
            'include/libxml/nanoftp.h',
            'include/libxml/nanohttp.h',
            'include/libxml/parser.h',
            'include/libxml/parserInternals.h',
            'include/libxml/pattern.h',
            'include/libxml/relaxng.h',
            'include/libxml/SAX.h',
            'include/libxml/SAX2.h',
            'include/libxml/schemasInternals.h',
            'include/libxml/schematron.h',
            'include/libxml/threads.h',
            'include/libxml/tree.h',
            'include/libxml/uri.h',
            'include/libxml/valid.h',
            'include/libxml/xinclude.h',
            'include/libxml/xlink.h',
            'include/libxml/xmlautomata.h',
            'include/libxml/xmlerror.h',
            'include/libxml/xmlexports.h',
            'include/libxml/xmlIO.h',
            'include/libxml/xmlmemory.h',
            'include/libxml/xmlmodule.h',
            'include/libxml/xmlreader.h',
            'include/libxml/xmlregexp.h',
            'include/libxml/xmlsave.h',
            'include/libxml/xmlschemas.h',
            'include/libxml/xmlschemastypes.h',
            'include/libxml/xmlstring.h',
            'include/libxml/xmlunicode.h',
            'include/libxml/xmlwriter.h',
            'include/libxml/xpath.h',
            'include/libxml/xpathInternals.h',
            'include/libxml/xpointer.h',
            'include/win32config.h',
            'include/wsockcompat.h',
            'linux/config.h',
            'linux/include/libxml/xmlversion.h',
            'mac/config.h',
            'mac/include/libxml/xmlversion.h',
            'win32/config.h',
            'win32/include/libxml/xmlversion.h',
            'acconfig.h',
            'c14n.c',
            'catalog.c',
            'chvalid.c',
            'debugXML.c',
            'dict.c',
            'DOCBparser.c',
            'elfgcchack.h',
            'encoding.c',
            'entities.c',
            'error.c',
            'globals.c',
            'hash.c',
            'HTMLparser.c',
            'HTMLtree.c',
            'legacy.c',
            'libxml.h',
            'list.c',
            'nanoftp.c',
            'nanohttp.c',
            'parser.c',
            'parserInternals.c',
            'pattern.c',
            'relaxng.c',
            'SAX.c',
            'SAX2.c',
            'schematron.c',
            'threads.c',
            'tree.c',
            #'trio.c',
            #'trio.h',
            #'triodef.h',
            #'trionan.c',
            #'trionan.h',
            #'triop.h',
            #'triostr.c',
            #'triostr.h',
            'uri.c',
            'valid.c',
            'xinclude.c',
            'xlink.c',
            'xmlIO.c',
            'xmlmemory.c',
            'xmlmodule.c',
            'xmlreader.c',
            'xmlregexp.c',
            'xmlsave.c',
            'xmlschemas.c',
            'xmlschemastypes.c',
            'xmlstring.c',
            'xmlunicode.c',
            'xmlwriter.c',
            'xpath.c',
            'xpointer.c',
          ],
          'include_dirs': [
            '<(os_include)',
            '<(os_include)/include',
            'include',
          ],
          'dependencies': [
            '../icu/icu.gyp:icuuc',
            '../zlib/zlib.gyp:zlib',
          ],
          'export_dependent_settings': [
            '../icu/icu.gyp:icuuc',
          ],
          'direct_dependent_settings': {
            'include_dirs': [
              '<(os_include)/include',
              'include',
            ],
          },
          'conditions': [
            ['OS=="linux"', {
              'link_settings': {
                'libraries': [
                  # We need dl for dlopen() and friends.
                  '-ldl',
                ],
              },
            }],
            ['OS=="mac"', {'defines': ['_REENTRANT']}],
            ['OS=="win"', {
              'product_name': 'libxml2',
            }, {  # else: OS!="win"
              'product_name': 'xml2',
            }],
          ],
        }],
      ],
    },
  ],
}

# Local Variables:
# tab-width:2
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=2 shiftwidth=2:
<commit_msg>Revert 53122 - libxml: LIBXML_STATIC isn't needed on windows either<commit_after># Copyright (c) 2009 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

{
  'variables': {
    'conditions': [
      ['OS=="linux" or OS=="freebsd" or OS=="openbsd" or OS=="solaris"', {
        'os_include': 'linux'
      }],
      ['OS=="mac"', {'os_include': 'mac'}],
      ['OS=="win"', {'os_include': 'win32'}],
    ],
    'use_system_libxml%': 0,
  },
  'targets': [
    {
      'target_name': 'libxml',
      'conditions': [
        ['(OS=="linux" or OS=="freebsd" or OS=="openbsd" or OS=="solaris") and use_system_libxml', {
          'type': 'settings',
          'direct_dependent_settings': {
            'cflags': [
              '<!@(pkg-config --cflags libxml-2.0)',
            ],
            'defines': [
              'USE_SYSTEM_LIBXML',
            ],
          },
          'link_settings': {
            'ldflags': [
              '<!@(pkg-config --libs-only-L --libs-only-other libxml-2.0)',
            ],
            'libraries': [
              '<!@(pkg-config --libs-only-l libxml-2.0)',
            ],
          },
        }, { # else: OS != "linux" or ! use_system_libxml
          'type': '<(library)',
          'msvs_guid': 'F9810DE8-CBC3-4605-A7B1-ECA2D5292FD7',
          'sources': [
            'include/libxml/c14n.h',
            'include/libxml/catalog.h',
            'include/libxml/chvalid.h',
            'include/libxml/debugXML.h',
            'include/libxml/dict.h',
            'include/libxml/DOCBparser.h',
            'include/libxml/encoding.h',
            'include/libxml/entities.h',
            'include/libxml/globals.h',
            'include/libxml/hash.h',
            'include/libxml/HTMLparser.h',
            'include/libxml/HTMLtree.h',
            'include/libxml/list.h',
            'include/libxml/nanoftp.h',
            'include/libxml/nanohttp.h',
            'include/libxml/parser.h',
            'include/libxml/parserInternals.h',
            'include/libxml/pattern.h',
            'include/libxml/relaxng.h',
            'include/libxml/SAX.h',
            'include/libxml/SAX2.h',
            'include/libxml/schemasInternals.h',
            'include/libxml/schematron.h',
            'include/libxml/threads.h',
            'include/libxml/tree.h',
            'include/libxml/uri.h',
            'include/libxml/valid.h',
            'include/libxml/xinclude.h',
            'include/libxml/xlink.h',
            'include/libxml/xmlautomata.h',
            'include/libxml/xmlerror.h',
            'include/libxml/xmlexports.h',
            'include/libxml/xmlIO.h',
            'include/libxml/xmlmemory.h',
            'include/libxml/xmlmodule.h',
            'include/libxml/xmlreader.h',
            'include/libxml/xmlregexp.h',
            'include/libxml/xmlsave.h',
            'include/libxml/xmlschemas.h',
            'include/libxml/xmlschemastypes.h',
            'include/libxml/xmlstring.h',
            'include/libxml/xmlunicode.h',
            'include/libxml/xmlwriter.h',
            'include/libxml/xpath.h',
            'include/libxml/xpathInternals.h',
            'include/libxml/xpointer.h',
            'include/win32config.h',
            'include/wsockcompat.h',
            'linux/config.h',
            'linux/include/libxml/xmlversion.h',
            'mac/config.h',
            'mac/include/libxml/xmlversion.h',
            'win32/config.h',
            'win32/include/libxml/xmlversion.h',
            'acconfig.h',
            'c14n.c',
            'catalog.c',
            'chvalid.c',
            'debugXML.c',
            'dict.c',
            'DOCBparser.c',
            'elfgcchack.h',
            'encoding.c',
            'entities.c',
            'error.c',
            'globals.c',
            'hash.c',
            'HTMLparser.c',
            'HTMLtree.c',
            'legacy.c',
            'libxml.h',
            'list.c',
            'nanoftp.c',
            'nanohttp.c',
            'parser.c',
            'parserInternals.c',
            'pattern.c',
            'relaxng.c',
            'SAX.c',
            'SAX2.c',
            'schematron.c',
            'threads.c',
            'tree.c',
            #'trio.c',
            #'trio.h',
            #'triodef.h',
            #'trionan.c',
            #'trionan.h',
            #'triop.h',
            #'triostr.c',
            #'triostr.h',
            'uri.c',
            'valid.c',
            'xinclude.c',
            'xlink.c',
            'xmlIO.c',
            'xmlmemory.c',
            'xmlmodule.c',
            'xmlreader.c',
            'xmlregexp.c',
            'xmlsave.c',
            'xmlschemas.c',
            'xmlschemastypes.c',
            'xmlstring.c',
            'xmlunicode.c',
            'xmlwriter.c',
            'xpath.c',
            'xpointer.c',
          ],
          'include_dirs': [
            '<(os_include)',
            '<(os_include)/include',
            'include',
          ],
          'dependencies': [
            '../icu/icu.gyp:icuuc',
            '../zlib/zlib.gyp:zlib',
          ],
          'export_dependent_settings': [
            '../icu/icu.gyp:icuuc',
          ],
          'direct_dependent_settings': {
            'include_dirs': [
              '<(os_include)/include',
              'include',
            ],
          },
          'conditions': [
            ['OS=="linux"', {
              'link_settings': {
                'libraries': [
                  # We need dl for dlopen() and friends.
                  '-ldl',
                ],
              },
            }],
            ['OS=="mac"', {'defines': ['_REENTRANT']}],
            ['OS=="win"', {
              'product_name': 'libxml2',
              'defines': [
                # This symbol prevents libxml from marking its functions with
                # __declspec(dllexport).
                'LIBXML_STATIC',
              ],
            }, {  # else: OS!="win"
              'product_name': 'xml2',
            }],
          ],
        }],
      ],
    },
  ],
}

# Local Variables:
# tab-width:2
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=2 shiftwidth=2:
<|endoftext|>


<commit_before>""" Rules to build Go code.

Go has a strong built-in concept of packages so it's probably a good idea to match Please
rules to Go packages.
"""

_GO_COMPILE_TOOL = 'compile' if CONFIG.GO_VERSION >= "1.5" else '6g'
_GO_LINK_TOOL = 'link' if CONFIG.GO_VERSION >= "1.5" else '6l'

# This is the command we use to provide include directories to the Go compiler.
# It's fairly brutal but since our model is that we completely specify all the dependencies
# it's valid to essentially allow it to pick up any of them.
_SRC_DIRS_CMD = 'SRC_DIRS=`find . -type d | grep -v "^\\.$" | sed -E -e "s|^./|-I |g"`'

# Commands for go_binary and go_test.
_ALL_GO_BINARY_CMDS = ' && '.join([
    _SRC_DIRS_CMD,
    'for i in `find . -name "*.a"`; do cp $i $(dirname $(dirname $i)); done',
    'go tool %s -trimpath $TMP_DIR -complete $SRC_DIRS -I . -o ${OUT}.6 $SRC' % _GO_COMPILE_TOOL,
    'go tool %s -tmpdir $TMP_DIR ${SRC_DIRS//-I/-L} -L . -o ${OUT} ' % _GO_LINK_TOOL,
])
_GO_BINARY_CMDS = {
    'dbg': _ALL_GO_BINARY_CMDS + ' ${OUT}.6',
    'opt': _ALL_GO_BINARY_CMDS + '-s -w ${OUT}.6',
}

# Commands for go_library, which differ a bit more by config.
_ALL_GO_LIBRARY_CMDS = {
    # Copies archives up a directory; this is needed in some cases depending on whether
    # the library matches the name of the directory it's in or not.
    'copy_cmd': 'for i in `find . -name "*.a"`; do cp $i $(dirname $(dirname $i)); done',
    # Invokes the Go compiler.
    'compile_cmd': 'go tool %s -trimpath $TMP_DIR -complete $SRC_DIRS -I . -pack -o $OUT ' % _GO_COMPILE_TOOL,
    # Annotates files for coverage
    'cover_cmd': 'for SRC in $SRCS; do mv -f $SRC _tmp.go; BN=$(basename $SRC); go tool cover -mode=set -var=GoCover_${BN//./_} _tmp.go > $SRC; done',
    'src_dirs_cmd': _SRC_DIRS_CMD,
}
# String it all together.
_GO_LIBRARY_CMDS = {
    'dbg': '%(src_dirs_cmd)s; %(copy_cmd)s && %(compile_cmd)s -N -l $SRCS' % _ALL_GO_LIBRARY_CMDS,
    'opt': '%(src_dirs_cmd)s; %(copy_cmd)s && %(compile_cmd)s $SRCS' % _ALL_GO_LIBRARY_CMDS,
    'cover': '%(src_dirs_cmd)s; %(copy_cmd)s && %(cover_cmd)s && %(compile_cmd)s $SRCS' % _ALL_GO_LIBRARY_CMDS,
}

def go_library(name, srcs, out=None, deps=None, visibility=None, test_only=False):
    """Generates a Go library which can be reused by other rules.

    Args:
      name (str): Name of the rule.
      srcs (list): Go source files to compile.
      out (str): Name of the output library to compile (defaults to name suffixed with .a)
      deps (list): Dependencies
      visibility (list): Visibility specification
      test_only (bool): If True, is only visible to test rules.
    """
    # go_test and cgo_library need access to the sources as well.
    filegroup(
        name='_%s#srcs' % name,
        srcs=srcs,
        exported_deps=deps,
        visibility=visibility,
        output_is_complete=False,
        requires=['go'],
        test_only=test_only,
    )
    build_rule(
        name=name,
        srcs=srcs,
        deps=(deps or []) + [':_%s#srcs' % name],
        outs=[out or name + '.a'],
        cmd=_GO_LIBRARY_CMDS,
        visibility=visibility,
        building_description="Compiling...",
        requires=['go'],
        provides={'go': ':' + name, 'go_src': ':_%s#srcs' % name},
        test_only=test_only,
    )

def cgo_library(name, srcs, env=None, deps=None, visibility=None, test_only=False, package=''):
    """Generates a Go library which can be reused by other rules.

    Note that this is a little experimental and hasn't yet received extensive testing.

    It also has a slightly interesting approach in that it recompiles all the input
    Go sources. It'd be nicer to use go tool cgo/compile, but it's excruciatingly
    hard to mimic what 'go build' does well enough to actually work.

    Args:
      name (str): Name of the rule.
      srcs (list): Go source files to compile.
      env (dict): Dict of environment variables to control the Go build.
      deps (list): Dependencies
      visibility (list): Visibility specification
      test_only (bool): If True, is only visible to test rules.
      package (str): Name of the package to output (defaults to same as name).
    """
    env = env or {}
    package = package or name
    # TODO(pebers): Need a sensible way of working out what GOPATH should be.
    env.setdefault('GOPATH', '$TMP_DIR:$TMP_DIR/third_party/go')
    env_cmd = ' '.join('export %s="%s";' % (k, v) for k, v in sorted(env.items()))
    cmd = ' && '.join([
        'if [ ! -d src ]; then ln -s . src; fi',
        'go install ${PKG#*src/}',
        'mv pkg/${OS}_${ARCH}/${PKG#*src/}.a $OUT',
    ])

    filegroup(
        name='_%s#srcs' % name,
        srcs=srcs,
        deps=deps,
        visibility=visibility,
        output_is_complete=False,
        requires=['go'],
        test_only=test_only,
    )

    build_rule(
        name=name,
        srcs=srcs,
        deps=(deps or []) + [':_%s#srcs' % name],
        outs=[package + '.a'],
        cmd=env_cmd + cmd,
        visibility=visibility,
        building_description="Compiling...",
        requires=['go', 'go_src', 'cc', 'cc_hdrs'],
        provides={
            'go': ':' + name,
            'go_src': ':_%s#srcs' % name,
        },
        test_only=test_only,
        needs_transitive_deps=True,
    )

def go_binary(name, main=None, deps=None, visibility=None, test_only=False):
    """Compiles a Go binary.

    Args:
      name (str): Name of the rule.
      main (str): Go source file containing the main function.
      deps (list): Dependencies
      visibility (list): Visibility specification
      test_only (bool): If True, is only visible to test rules.
    """
    build_rule(
        name=name,
        srcs=[main or name + '.go'],
        deps=deps,
        outs=[name],
        cmd=_GO_BINARY_CMDS,
        building_description="Compiling...",
        needs_transitive_deps=True,
        binary=True,
        output_is_complete=True,
        test_only=test_only,
        visibility=visibility,
        requires=['go'],
    )

def go_test(name, srcs, data=None, deps=None, visibility=None, container=False,
            timeout=0, flaky=0, test_outputs=None, labels=None):
    """Defines a Go test rule.

    Args:
      name (str): Name of the rule.
      srcs (list): Go source files to compile.
      data (list): Runtime data files for the test.
      deps (list): Dependencies
      visibility (list): Visibility specification
      container (bool | dict): True to run this test in a container.
      timeout (int): Timeout in seconds to allow the test to run for.
      flaky (int | bool): True to mark the test as flaky, or an integer to specify how many reruns.
      test_outputs (list): Extra test output files to generate from this test.
      labels (list): Labels for this rule.
    """
    # Unfortunately we have to recompile this to build the test together with its library.
    build_rule(
        name='_%s#lib' % name,
        srcs=srcs,
        deps=deps,
        outs=[name + '.a'],
        cmd={k: 'SRCS=${PKG}/*.go; ' + v for k, v in _GO_LIBRARY_CMDS.items()},
        building_description="Compiling...",
        requires=['go', 'go_src'],
        test_only=True,
        # TODO(pebers): We should be able to get away without this via a judicious
        #               exported_deps in go_library, but it doesn't seem to be working.
        needs_transitive_deps=True,
    )
    go_test_tool, tools = _tool_path(CONFIG.GO_TEST_TOOL)
    build_rule(
        name='_%s#main' % name,
        srcs=srcs,
        outs=[name + '_main.go'],
        deps=deps,
        cmd={
            'dbg': go_test_tool + ' -o $OUT $SRCS',
            'opt': go_test_tool + ' -o $OUT $SRCS',
            'cover': go_test_tool + ' -d . -o $OUT $SRCS ',
        },
        needs_transitive_deps=True,  # Need all .a files to template coverage variables
        requires=['go'],
        tools=tools,
        post_build=_replace_test_package,
    )
    build_rule(
        name=name,
        srcs=[':_%s#main' % name],
        data=data,
        deps=(deps or []) + [':_%s#lib' % name],
        outs=[name],
        cmd=_GO_BINARY_CMDS,
        test_cmd='bash -c "set -o pipefail && $(exe :%s) | tee test.results"' % name,
        visibility=visibility,
        container=container,
        test_timeout=timeout,
        flaky=flaky,
        test_outputs=test_outputs,
        requires=['go'],
        labels=labels,
        binary=True,
        test=True,
        building_description="Compiling...",
        needs_transitive_deps=True,
        output_is_complete=True,
    )

def cgo_test(name, srcs, data=None, deps=None, visibility=None, container=False,
             timeout=0, flaky=0, test_outputs=None, labels=None, tags=None):
    """Defines a Go test rule for a library that uses cgo.

    If the library you are testing is a cgo_library, you must use this instead of go_test.
    It's ok to depend on a cgo_library though as long as it's not the same package
    as your test.

    Args:
      name (str): Name of the rule.
      srcs (list): Go source files to compile.
      data (list): Runtime data files for the test.
      deps (list): Dependencies
      visibility (list): Visibility specification
      container (bool | dict): True to run this test in a container.
      timeout (int): Timeout in seconds to allow the test to run for.
      flaky (int | bool): True to mark the test as flaky, or an integer to specify how many reruns.
      test_outputs (list): Extra test output files to generate from this test.
      labels (list): Labels for this rule.
      tags (list): Tags to pass to go build (see 'go help build' for details).
    """
    tag_cmd = '-tags "%s"' % ' '.join(tags) if tags else ''
    build_rule(
        name=name,
        srcs=srcs,
        data=data,
        deps=deps,
        outs=[name],
        # TODO(pebers): how not to hardcode third_party/go here?
        cmd='export GOPATH=${PWD}:${PWD}/third_party/go; ln -s $TMP_DIR src; go test ${PKG#*src/} %s -c -test.cover -o $OUT' % tag_cmd,
        test_cmd='set -o pipefail && $(exe :%s) -test.v -test.coverprofile test.coverage | tee test.results' % name,
        visibility=visibility,
        container=container,
        test_timeout=timeout,
        flaky=flaky,
        test_outputs=test_outputs,
        requires=['go', 'go_src'],
        labels=labels,
        binary=True,
        test=True,
        building_description="Compiling...",
        needs_transitive_deps=True,
        output_is_complete=True,
    )

def go_get(name, get=None, outs=None, deps=None, visibility=None, patch=None,
           binary=False, test_only=False, install=None, revision=None):
    """Defines a dependency on a third-party Go library.

    Args:
      name (str): Name of the rule
      get (str): Target to get (eg. "github.com/gorilla/mux")
      outs (list): Output files from the rule. Default autodetects.
      deps (list): Dependencies
      visibility (list): Visibility specification
      patch (str): Patch file to apply
      binary (bool): True if the output of the rule is a binary.
      test_only (bool): If true this rule will only be visible to tests.
      install (list): Allows specifying extra packages to install. Convenient in some cases where we
                      want to go get something with an extra subpackage.
      revision (str): Git hash to check out before building. Only works for git at present,
                      not for other version control systems.
    """
    post_build = None
    if binary and outs and len(outs) != 1:
        raise ValueError(name + ': Binary rules can only have a single output')
    if not outs:
        outs = [('bin/' + name) if binary else ('src/' + get)]
        if not binary:
            post_build = _extra_outs(get)
    cmd = [
        'export GOPATH=$TMP_DIR:$TMP_DIR/$PKG',
        'rm -rf pkg src',
        'go get -d ' + get,
    ]
    subdir = 'src/' + (get[:-4] if get.endswith('/...') else get)
    if revision:
        # Annoyingly -C does not work on git checkout :(
        cmd.append('(cd %s && git checkout -q %s)' % (subdir, revision))
    if patch:
        cmd.append('patch -s -d %s -p1 < ${TMP_DIR}/$(location %s)' % (subdir, patch))
    cmd.append('go install ' + get)
    if install:
        cmd.extend('go install %s' % lib for lib in install)
    cmd.extend([
        'find . -name .git | xargs rm -rf',
        'find pkg -name "*.a"',
    ])
    build_rule(
        name=name,
        srcs=[patch] if patch else [],
        outs=outs,
        deps=deps,
        visibility=visibility,
        building_description='Fetching...',
        cmd=' && '.join(cmd),
        binary=binary,
        requires=['go'],
        test_only=test_only,
        post_build=post_build,
    )

def _extra_outs(get):
    """Attaches extra outputs to go_get rules."""
    def _inner(name, output):
        last = '<>'
        for archive in sorted(output):
            add_out(name, archive)
            subpath = archive[archive.find('/', 6) + 1:-2]
            if not subpath.startswith(get) and not subpath.startswith(last):
                add_out(name, 'src/' + subpath)
            last = subpath
    return _inner

def _replace_test_package(name, output):
    """Post-build function, called after we template the main function.

    The purpose is to replace the real library with the specific one we've
    built for this test which has the actual test functions in it.
    """
    if not name.endswith('#main') or not name.startswith('_'):
        raise ValueError('unexpected rule name: ' + name)
    name = name[1:-5]
    for line in output:
        if line.startswith('Package: '):
            for k, v in _GO_BINARY_CMDS.items():
                set_command(name, k, 'mv -f ${PKG}/%s.a ${PKG}/%s.a && %s' % (name, line[9:], v))
<commit_msg>Removes unnecessary bash -c<commit_after>""" Rules to build Go code.

Go has a strong built-in concept of packages so it's probably a good idea to match Please
rules to Go packages.
"""

_GO_COMPILE_TOOL = 'compile' if CONFIG.GO_VERSION >= "1.5" else '6g'
_GO_LINK_TOOL = 'link' if CONFIG.GO_VERSION >= "1.5" else '6l'

# This is the command we use to provide include directories to the Go compiler.
# It's fairly brutal but since our model is that we completely specify all the dependencies
# it's valid to essentially allow it to pick up any of them.
_SRC_DIRS_CMD = 'SRC_DIRS=`find . -type d | grep -v "^\\.$" | sed -E -e "s|^./|-I |g"`'

# Commands for go_binary and go_test.
_ALL_GO_BINARY_CMDS = ' && '.join([
    _SRC_DIRS_CMD,
    'for i in `find . -name "*.a"`; do cp $i $(dirname $(dirname $i)); done',
    'go tool %s -trimpath $TMP_DIR -complete $SRC_DIRS -I . -o ${OUT}.6 $SRC' % _GO_COMPILE_TOOL,
    'go tool %s -tmpdir $TMP_DIR ${SRC_DIRS//-I/-L} -L . -o ${OUT} ' % _GO_LINK_TOOL,
])
_GO_BINARY_CMDS = {
    'dbg': _ALL_GO_BINARY_CMDS + ' ${OUT}.6',
    'opt': _ALL_GO_BINARY_CMDS + '-s -w ${OUT}.6',
}

# Commands for go_library, which differ a bit more by config.
_ALL_GO_LIBRARY_CMDS = {
    # Copies archives up a directory; this is needed in some cases depending on whether
    # the library matches the name of the directory it's in or not.
    'copy_cmd': 'for i in `find . -name "*.a"`; do cp $i $(dirname $(dirname $i)); done',
    # Invokes the Go compiler.
    'compile_cmd': 'go tool %s -trimpath $TMP_DIR -complete $SRC_DIRS -I . -pack -o $OUT ' % _GO_COMPILE_TOOL,
    # Annotates files for coverage
    'cover_cmd': 'for SRC in $SRCS; do mv -f $SRC _tmp.go; BN=$(basename $SRC); go tool cover -mode=set -var=GoCover_${BN//./_} _tmp.go > $SRC; done',
    'src_dirs_cmd': _SRC_DIRS_CMD,
}
# String it all together.
_GO_LIBRARY_CMDS = {
    'dbg': '%(src_dirs_cmd)s; %(copy_cmd)s && %(compile_cmd)s -N -l $SRCS' % _ALL_GO_LIBRARY_CMDS,
    'opt': '%(src_dirs_cmd)s; %(copy_cmd)s && %(compile_cmd)s $SRCS' % _ALL_GO_LIBRARY_CMDS,
    'cover': '%(src_dirs_cmd)s; %(copy_cmd)s && %(cover_cmd)s && %(compile_cmd)s $SRCS' % _ALL_GO_LIBRARY_CMDS,
}

def go_library(name, srcs, out=None, deps=None, visibility=None, test_only=False):
    """Generates a Go library which can be reused by other rules.

    Args:
      name (str): Name of the rule.
      srcs (list): Go source files to compile.
      out (str): Name of the output library to compile (defaults to name suffixed with .a)
      deps (list): Dependencies
      visibility (list): Visibility specification
      test_only (bool): If True, is only visible to test rules.
    """
    # go_test and cgo_library need access to the sources as well.
    filegroup(
        name='_%s#srcs' % name,
        srcs=srcs,
        exported_deps=deps,
        visibility=visibility,
        output_is_complete=False,
        requires=['go'],
        test_only=test_only,
    )
    build_rule(
        name=name,
        srcs=srcs,
        deps=(deps or []) + [':_%s#srcs' % name],
        outs=[out or name + '.a'],
        cmd=_GO_LIBRARY_CMDS,
        visibility=visibility,
        building_description="Compiling...",
        requires=['go'],
        provides={'go': ':' + name, 'go_src': ':_%s#srcs' % name},
        test_only=test_only,
    )

def cgo_library(name, srcs, env=None, deps=None, visibility=None, test_only=False, package=''):
    """Generates a Go library which can be reused by other rules.

    Note that this is a little experimental and hasn't yet received extensive testing.

    It also has a slightly interesting approach in that it recompiles all the input
    Go sources. It'd be nicer to use go tool cgo/compile, but it's excruciatingly
    hard to mimic what 'go build' does well enough to actually work.

    Args:
      name (str): Name of the rule.
      srcs (list): Go source files to compile.
      env (dict): Dict of environment variables to control the Go build.
      deps (list): Dependencies
      visibility (list): Visibility specification
      test_only (bool): If True, is only visible to test rules.
      package (str): Name of the package to output (defaults to same as name).
    """
    env = env or {}
    package = package or name
    # TODO(pebers): Need a sensible way of working out what GOPATH should be.
    env.setdefault('GOPATH', '$TMP_DIR:$TMP_DIR/third_party/go')
    env_cmd = ' '.join('export %s="%s";' % (k, v) for k, v in sorted(env.items()))
    cmd = ' && '.join([
        'if [ ! -d src ]; then ln -s . src; fi',
        'go install ${PKG#*src/}',
        'mv pkg/${OS}_${ARCH}/${PKG#*src/}.a $OUT',
    ])

    filegroup(
        name='_%s#srcs' % name,
        srcs=srcs,
        deps=deps,
        visibility=visibility,
        output_is_complete=False,
        requires=['go'],
        test_only=test_only,
    )

    build_rule(
        name=name,
        srcs=srcs,
        deps=(deps or []) + [':_%s#srcs' % name],
        outs=[package + '.a'],
        cmd=env_cmd + cmd,
        visibility=visibility,
        building_description="Compiling...",
        requires=['go', 'go_src', 'cc', 'cc_hdrs'],
        provides={
            'go': ':' + name,
            'go_src': ':_%s#srcs' % name,
        },
        test_only=test_only,
        needs_transitive_deps=True,
    )

def go_binary(name, main=None, deps=None, visibility=None, test_only=False):
    """Compiles a Go binary.

    Args:
      name (str): Name of the rule.
      main (str): Go source file containing the main function.
      deps (list): Dependencies
      visibility (list): Visibility specification
      test_only (bool): If True, is only visible to test rules.
    """
    build_rule(
        name=name,
        srcs=[main or name + '.go'],
        deps=deps,
        outs=[name],
        cmd=_GO_BINARY_CMDS,
        building_description="Compiling...",
        needs_transitive_deps=True,
        binary=True,
        output_is_complete=True,
        test_only=test_only,
        visibility=visibility,
        requires=['go'],
    )

def go_test(name, srcs, data=None, deps=None, visibility=None, container=False,
            timeout=0, flaky=0, test_outputs=None, labels=None):
    """Defines a Go test rule.

    Args:
      name (str): Name of the rule.
      srcs (list): Go source files to compile.
      data (list): Runtime data files for the test.
      deps (list): Dependencies
      visibility (list): Visibility specification
      container (bool | dict): True to run this test in a container.
      timeout (int): Timeout in seconds to allow the test to run for.
      flaky (int | bool): True to mark the test as flaky, or an integer to specify how many reruns.
      test_outputs (list): Extra test output files to generate from this test.
      labels (list): Labels for this rule.
    """
    # Unfortunately we have to recompile this to build the test together with its library.
    build_rule(
        name='_%s#lib' % name,
        srcs=srcs,
        deps=deps,
        outs=[name + '.a'],
        cmd={k: 'SRCS=${PKG}/*.go; ' + v for k, v in _GO_LIBRARY_CMDS.items()},
        building_description="Compiling...",
        requires=['go', 'go_src'],
        test_only=True,
        # TODO(pebers): We should be able to get away without this via a judicious
        #               exported_deps in go_library, but it doesn't seem to be working.
        needs_transitive_deps=True,
    )
    go_test_tool, tools = _tool_path(CONFIG.GO_TEST_TOOL)
    build_rule(
        name='_%s#main' % name,
        srcs=srcs,
        outs=[name + '_main.go'],
        deps=deps,
        cmd={
            'dbg': go_test_tool + ' -o $OUT $SRCS',
            'opt': go_test_tool + ' -o $OUT $SRCS',
            'cover': go_test_tool + ' -d . -o $OUT $SRCS ',
        },
        needs_transitive_deps=True,  # Need all .a files to template coverage variables
        requires=['go'],
        tools=tools,
        post_build=_replace_test_package,
    )
    build_rule(
        name=name,
        srcs=[':_%s#main' % name],
        data=data,
        deps=(deps or []) + [':_%s#lib' % name],
        outs=[name],
        cmd=_GO_BINARY_CMDS,
        test_cmd='set -o pipefail && $(exe :%s) | tee test.results' % name,
        visibility=visibility,
        container=container,
        test_timeout=timeout,
        flaky=flaky,
        test_outputs=test_outputs,
        requires=['go'],
        labels=labels,
        binary=True,
        test=True,
        building_description="Compiling...",
        needs_transitive_deps=True,
        output_is_complete=True,
    )

def cgo_test(name, srcs, data=None, deps=None, visibility=None, container=False,
             timeout=0, flaky=0, test_outputs=None, labels=None, tags=None):
    """Defines a Go test rule for a library that uses cgo.

    If the library you are testing is a cgo_library, you must use this instead of go_test.
    It's ok to depend on a cgo_library though as long as it's not the same package
    as your test.

    Args:
      name (str): Name of the rule.
      srcs (list): Go source files to compile.
      data (list): Runtime data files for the test.
      deps (list): Dependencies
      visibility (list): Visibility specification
      container (bool | dict): True to run this test in a container.
      timeout (int): Timeout in seconds to allow the test to run for.
      flaky (int | bool): True to mark the test as flaky, or an integer to specify how many reruns.
      test_outputs (list): Extra test output files to generate from this test.
      labels (list): Labels for this rule.
      tags (list): Tags to pass to go build (see 'go help build' for details).
    """
    tag_cmd = '-tags "%s"' % ' '.join(tags) if tags else ''
    build_rule(
        name=name,
        srcs=srcs,
        data=data,
        deps=deps,
        outs=[name],
        # TODO(pebers): how not to hardcode third_party/go here?
        cmd='export GOPATH=${PWD}:${PWD}/third_party/go; ln -s $TMP_DIR src; go test ${PKG#*src/} %s -c -test.cover -o $OUT' % tag_cmd,
        test_cmd='set -o pipefail && $(exe :%s) -test.v -test.coverprofile test.coverage | tee test.results' % name,
        visibility=visibility,
        container=container,
        test_timeout=timeout,
        flaky=flaky,
        test_outputs=test_outputs,
        requires=['go', 'go_src'],
        labels=labels,
        binary=True,
        test=True,
        building_description="Compiling...",
        needs_transitive_deps=True,
        output_is_complete=True,
    )

def go_get(name, get=None, outs=None, deps=None, visibility=None, patch=None,
           binary=False, test_only=False, install=None, revision=None):
    """Defines a dependency on a third-party Go library.

    Args:
      name (str): Name of the rule
      get (str): Target to get (eg. "github.com/gorilla/mux")
      outs (list): Output files from the rule. Default autodetects.
      deps (list): Dependencies
      visibility (list): Visibility specification
      patch (str): Patch file to apply
      binary (bool): True if the output of the rule is a binary.
      test_only (bool): If true this rule will only be visible to tests.
      install (list): Allows specifying extra packages to install. Convenient in some cases where we
                      want to go get something with an extra subpackage.
      revision (str): Git hash to check out before building. Only works for git at present,
                      not for other version control systems.
    """
    post_build = None
    if binary and outs and len(outs) != 1:
        raise ValueError(name + ': Binary rules can only have a single output')
    if not outs:
        outs = [('bin/' + name) if binary else ('src/' + get)]
        if not binary:
            post_build = _extra_outs(get)
    cmd = [
        'export GOPATH=$TMP_DIR:$TMP_DIR/$PKG',
        'rm -rf pkg src',
        'go get -d ' + get,
    ]
    subdir = 'src/' + (get[:-4] if get.endswith('/...') else get)
    if revision:
        # Annoyingly -C does not work on git checkout :(
        cmd.append('(cd %s && git checkout -q %s)' % (subdir, revision))
    if patch:
        cmd.append('patch -s -d %s -p1 < ${TMP_DIR}/$(location %s)' % (subdir, patch))
    cmd.append('go install ' + get)
    if install:
        cmd.extend('go install %s' % lib for lib in install)
    cmd.extend([
        'find . -name .git | xargs rm -rf',
        'find pkg -name "*.a"',
    ])
    build_rule(
        name=name,
        srcs=[patch] if patch else [],
        outs=outs,
        deps=deps,
        visibility=visibility,
        building_description='Fetching...',
        cmd=' && '.join(cmd),
        binary=binary,
        requires=['go'],
        test_only=test_only,
        post_build=post_build,
    )

def _extra_outs(get):
    """Attaches extra outputs to go_get rules."""
    def _inner(name, output):
        last = '<>'
        for archive in sorted(output):
            add_out(name, archive)
            subpath = archive[archive.find('/', 6) + 1:-2]
            if not subpath.startswith(get) and not subpath.startswith(last):
                add_out(name, 'src/' + subpath)
            last = subpath
    return _inner

def _replace_test_package(name, output):
    """Post-build function, called after we template the main function.

    The purpose is to replace the real library with the specific one we've
    built for this test which has the actual test functions in it.
    """
    if not name.endswith('#main') or not name.startswith('_'):
        raise ValueError('unexpected rule name: ' + name)
    name = name[1:-5]
    for line in output:
        if line.startswith('Package: '):
            for k, v in _GO_BINARY_CMDS.items():
                set_command(name, k, 'mv -f ${PKG}/%s.a ${PKG}/%s.a && %s' % (name, line[9:], v))
<|endoftext|>


<commit_before># Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

{
  'variables': {
    'conditions': [
      # Define an "os_include" variable that points at the OS-specific generated
      # headers.  These were generated by running the configure script offline.
      ['os_posix == 1 and OS != "mac" and OS != "ios"', {
        'os_include': 'linux'
      }],
      ['OS=="mac"', {'os_include': 'mac'}],
      ['OS=="win"', {'os_include': 'win32'}],
    ],
    'use_system_libxml%': 0,
  },
  'targets': [
    {
      'target_name': 'libxml',
      'conditions': [
        ['use_system_libxml', {
          'conditions': [
            ['os_posix == 1 and OS != "mac" and OS != "ios"', {
              'type': 'static_library',
              'sources': [
                'chromium/libxml_utils.h',
                'chromium/libxml_utils.cc',
              ],
              'cflags': [
                '<!@(pkg-config --cflags libxml-2.0)',
              ],
              'defines': [
                'USE_SYSTEM_LIBXML',
              ],
              'direct_dependent_settings': {
                'cflags': [
                  '<!@(pkg-config --cflags libxml-2.0)',
                ],
                'defines': [
                  'USE_SYSTEM_LIBXML',
                ],
              },
              'link_settings': {
                'ldflags': [
                  '<!@(pkg-config --libs-only-L --libs-only-other libxml-2.0)',
                ],
                'libraries': [
                  '<!@(pkg-config --libs-only-l libxml-2.0)',
                ],
              },
            }],
            ['OS == "ios"', {
              'type': 'none',
              'all_dependent_settings': {
                'defines': [
                  'USE_SYSTEM_LIBXML',
                ],
                'include_dirs': [
                  '$(SDKROOT)/usr/include/libxml2',
                ],
              },
              'link_settings': {
                'libraries': [
                  '$(SDKROOT)/usr/lib/libxml2.dylib',
                ],
              },
            }],
          ],
        }, {  # else: !use_system_libxml
          'type': 'static_library',
          'sources': [
            'chromium/libxml_utils.h',
            'chromium/libxml_utils.cc',
            'linux/config.h',
            'linux/include/libxml/xmlversion.h',
            'mac/config.h',
            'mac/include/libxml/xmlversion.h',
            'src/include/libxml/c14n.h',
            'src/include/libxml/catalog.h',
            'src/include/libxml/chvalid.h',
            'src/include/libxml/debugXML.h',
            'src/include/libxml/dict.h',
            'src/include/libxml/DOCBparser.h',
            'src/include/libxml/encoding.h',
            'src/include/libxml/entities.h',
            'src/include/libxml/globals.h',
            'src/include/libxml/hash.h',
            'src/include/libxml/HTMLparser.h',
            'src/include/libxml/HTMLtree.h',
            'src/include/libxml/list.h',
            'src/include/libxml/nanoftp.h',
            'src/include/libxml/nanohttp.h',
            'src/include/libxml/parser.h',
            'src/include/libxml/parserInternals.h',
            'src/include/libxml/pattern.h',
            'src/include/libxml/relaxng.h',
            'src/include/libxml/SAX.h',
            'src/include/libxml/SAX2.h',
            'src/include/libxml/schemasInternals.h',
            'src/include/libxml/schematron.h',
            'src/include/libxml/threads.h',
            'src/include/libxml/tree.h',
            'src/include/libxml/uri.h',
            'src/include/libxml/valid.h',
            'src/include/libxml/xinclude.h',
            'src/include/libxml/xlink.h',
            'src/include/libxml/xmlautomata.h',
            'src/include/libxml/xmlerror.h',
            'src/include/libxml/xmlexports.h',
            'src/include/libxml/xmlIO.h',
            'src/include/libxml/xmlmemory.h',
            'src/include/libxml/xmlmodule.h',
            'src/include/libxml/xmlreader.h',
            'src/include/libxml/xmlregexp.h',
            'src/include/libxml/xmlsave.h',
            'src/include/libxml/xmlschemas.h',
            'src/include/libxml/xmlschemastypes.h',
            'src/include/libxml/xmlstring.h',
            'src/include/libxml/xmlunicode.h',
            'src/include/libxml/xmlwriter.h',
            'src/include/libxml/xpath.h',
            'src/include/libxml/xpathInternals.h',
            'src/include/libxml/xpointer.h',
            'src/include/win32config.h',
            'src/include/wsockcompat.h',
            'src/acconfig.h',
            'src/c14n.c',
            'src/catalog.c',
            'src/chvalid.c',
            'src/debugXML.c',
            'src/dict.c',
            'src/DOCBparser.c',
            'src/elfgcchack.h',
            'src/encoding.c',
            'src/entities.c',
            'src/error.c',
            'src/globals.c',
            'src/hash.c',
            'src/HTMLparser.c',
            'src/HTMLtree.c',
            'src/legacy.c',
            'src/libxml.h',
            'src/list.c',
            'src/nanoftp.c',
            'src/nanohttp.c',
            'src/parser.c',
            'src/parserInternals.c',
            'src/pattern.c',
            'src/relaxng.c',
            'src/SAX.c',
            'src/SAX2.c',
            'src/schematron.c',
            'src/threads.c',
            'src/tree.c',
            #'src/trio.c',
            #'src/trio.h',
            #'src/triodef.h',
            #'src/trionan.c',
            #'src/trionan.h',
            #'src/triop.h',
            #'src/triostr.c',
            #'src/triostr.h',
            'src/uri.c',
            'src/valid.c',
            'src/xinclude.c',
            'src/xlink.c',
            'src/xmlIO.c',
            'src/xmlmemory.c',
            'src/xmlmodule.c',
            'src/xmlreader.c',
            'src/xmlregexp.c',
            'src/xmlsave.c',
            'src/xmlschemas.c',
            'src/xmlschemastypes.c',
            'src/xmlstring.c',
            'src/xmlunicode.c',
            'src/xmlwriter.c',
            'src/xpath.c',
            'src/xpointer.c',
            'win32/config.h',
            'win32/include/libxml/xmlversion.h',
          ],
          'defines': [
            # Define LIBXML_STATIC as nothing to match how libxml.h
            # (an internal header) defines LIBXML_STATIC, otherwise
            # we get the macro redefined warning from GCC.  (-DFOO
            # defines the macro FOO as 1.)
            'LIBXML_STATIC=',
          ],
          'include_dirs': [
            '<(os_include)',
            '<(os_include)/include',
            'src/include',
          ],
          'dependencies': [
            '../icu/icu.gyp:icuuc',
            '../zlib/zlib.gyp:zlib',
          ],
          'export_dependent_settings': [
            '../icu/icu.gyp:icuuc',
          ],
          'direct_dependent_settings': {
            'defines': [
              'LIBXML_STATIC',
            ],
            'include_dirs': [
              '<(os_include)/include',
              'src/include',
            ],
          },
          'conditions': [
            ['OS=="linux"', {
              'link_settings': {
                'libraries': [
                  # We need dl for dlopen() and friends.
                  '-ldl',
                ],
              },
            }],
            # http://www.xmlsoft.org/threads.html says that this is required
            # when using libxml from several threads, which can possibly happen
            # in chrome. On linux, this is picked up by transitivity from
            # pkg-config output from build/linux/system.gyp.
            ['OS=="mac" or OS=="android"', {'defines': ['_REENTRANT']}],
            ['OS=="win"', {
              'product_name': 'libxml2',
              # Disable unimportant 'unused variable' warning, and
              # signed/unsigned comparison warning. The signed/unsigned (4101)
              # is fixed upstream and can be removed eventually.
              'msvs_disabled_warnings': [ 4018, 4101 ],
            }, {  # else: OS!="win"
              'product_name': 'xml2',
            }],
            ['clang == 1', {
              'xcode_settings': {
                'WARNING_CFLAGS': [
                  # libxml passes `const unsigned char*` through `const char*`.
                  '-Wno-pointer-sign',
                  # pattern.c and uri.c both have an intentional
                  # `for (...);` / `while(...);` loop. I submitted a patch to
                  # move the `'` to its own line, but until that's landed
                  # suppress the warning:
                  '-Wno-empty-body',
                ],
              },
              'cflags': [
                '-Wno-pointer-sign',
                '-Wno-empty-body',

                # See http://crbug.com/138571#c8
                '-Wno-ignored-attributes',
              ],
            }],
          ],
        }],
      ],
    },
  ],
}
<commit_msg>disable c4267 for libxml for building on win x64<commit_after># Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

{
  'variables': {
    'conditions': [
      # Define an "os_include" variable that points at the OS-specific generated
      # headers.  These were generated by running the configure script offline.
      ['os_posix == 1 and OS != "mac" and OS != "ios"', {
        'os_include': 'linux'
      }],
      ['OS=="mac"', {'os_include': 'mac'}],
      ['OS=="win"', {'os_include': 'win32'}],
    ],
    'use_system_libxml%': 0,
  },
  'targets': [
    {
      'target_name': 'libxml',
      'conditions': [
        ['use_system_libxml', {
          'conditions': [
            ['os_posix == 1 and OS != "mac" and OS != "ios"', {
              'type': 'static_library',
              'sources': [
                'chromium/libxml_utils.h',
                'chromium/libxml_utils.cc',
              ],
              'cflags': [
                '<!@(pkg-config --cflags libxml-2.0)',
              ],
              'defines': [
                'USE_SYSTEM_LIBXML',
              ],
              'direct_dependent_settings': {
                'cflags': [
                  '<!@(pkg-config --cflags libxml-2.0)',
                ],
                'defines': [
                  'USE_SYSTEM_LIBXML',
                ],
              },
              'link_settings': {
                'ldflags': [
                  '<!@(pkg-config --libs-only-L --libs-only-other libxml-2.0)',
                ],
                'libraries': [
                  '<!@(pkg-config --libs-only-l libxml-2.0)',
                ],
              },
            }],
            ['OS == "ios"', {
              'type': 'none',
              'all_dependent_settings': {
                'defines': [
                  'USE_SYSTEM_LIBXML',
                ],
                'include_dirs': [
                  '$(SDKROOT)/usr/include/libxml2',
                ],
              },
              'link_settings': {
                'libraries': [
                  '$(SDKROOT)/usr/lib/libxml2.dylib',
                ],
              },
            }],
          ],
        }, {  # else: !use_system_libxml
          'type': 'static_library',
          'sources': [
            'chromium/libxml_utils.h',
            'chromium/libxml_utils.cc',
            'linux/config.h',
            'linux/include/libxml/xmlversion.h',
            'mac/config.h',
            'mac/include/libxml/xmlversion.h',
            'src/include/libxml/c14n.h',
            'src/include/libxml/catalog.h',
            'src/include/libxml/chvalid.h',
            'src/include/libxml/debugXML.h',
            'src/include/libxml/dict.h',
            'src/include/libxml/DOCBparser.h',
            'src/include/libxml/encoding.h',
            'src/include/libxml/entities.h',
            'src/include/libxml/globals.h',
            'src/include/libxml/hash.h',
            'src/include/libxml/HTMLparser.h',
            'src/include/libxml/HTMLtree.h',
            'src/include/libxml/list.h',
            'src/include/libxml/nanoftp.h',
            'src/include/libxml/nanohttp.h',
            'src/include/libxml/parser.h',
            'src/include/libxml/parserInternals.h',
            'src/include/libxml/pattern.h',
            'src/include/libxml/relaxng.h',
            'src/include/libxml/SAX.h',
            'src/include/libxml/SAX2.h',
            'src/include/libxml/schemasInternals.h',
            'src/include/libxml/schematron.h',
            'src/include/libxml/threads.h',
            'src/include/libxml/tree.h',
            'src/include/libxml/uri.h',
            'src/include/libxml/valid.h',
            'src/include/libxml/xinclude.h',
            'src/include/libxml/xlink.h',
            'src/include/libxml/xmlautomata.h',
            'src/include/libxml/xmlerror.h',
            'src/include/libxml/xmlexports.h',
            'src/include/libxml/xmlIO.h',
            'src/include/libxml/xmlmemory.h',
            'src/include/libxml/xmlmodule.h',
            'src/include/libxml/xmlreader.h',
            'src/include/libxml/xmlregexp.h',
            'src/include/libxml/xmlsave.h',
            'src/include/libxml/xmlschemas.h',
            'src/include/libxml/xmlschemastypes.h',
            'src/include/libxml/xmlstring.h',
            'src/include/libxml/xmlunicode.h',
            'src/include/libxml/xmlwriter.h',
            'src/include/libxml/xpath.h',
            'src/include/libxml/xpathInternals.h',
            'src/include/libxml/xpointer.h',
            'src/include/win32config.h',
            'src/include/wsockcompat.h',
            'src/acconfig.h',
            'src/c14n.c',
            'src/catalog.c',
            'src/chvalid.c',
            'src/debugXML.c',
            'src/dict.c',
            'src/DOCBparser.c',
            'src/elfgcchack.h',
            'src/encoding.c',
            'src/entities.c',
            'src/error.c',
            'src/globals.c',
            'src/hash.c',
            'src/HTMLparser.c',
            'src/HTMLtree.c',
            'src/legacy.c',
            'src/libxml.h',
            'src/list.c',
            'src/nanoftp.c',
            'src/nanohttp.c',
            'src/parser.c',
            'src/parserInternals.c',
            'src/pattern.c',
            'src/relaxng.c',
            'src/SAX.c',
            'src/SAX2.c',
            'src/schematron.c',
            'src/threads.c',
            'src/tree.c',
            #'src/trio.c',
            #'src/trio.h',
            #'src/triodef.h',
            #'src/trionan.c',
            #'src/trionan.h',
            #'src/triop.h',
            #'src/triostr.c',
            #'src/triostr.h',
            'src/uri.c',
            'src/valid.c',
            'src/xinclude.c',
            'src/xlink.c',
            'src/xmlIO.c',
            'src/xmlmemory.c',
            'src/xmlmodule.c',
            'src/xmlreader.c',
            'src/xmlregexp.c',
            'src/xmlsave.c',
            'src/xmlschemas.c',
            'src/xmlschemastypes.c',
            'src/xmlstring.c',
            'src/xmlunicode.c',
            'src/xmlwriter.c',
            'src/xpath.c',
            'src/xpointer.c',
            'win32/config.h',
            'win32/include/libxml/xmlversion.h',
          ],
          'defines': [
            # Define LIBXML_STATIC as nothing to match how libxml.h
            # (an internal header) defines LIBXML_STATIC, otherwise
            # we get the macro redefined warning from GCC.  (-DFOO
            # defines the macro FOO as 1.)
            'LIBXML_STATIC=',
          ],
          'include_dirs': [
            '<(os_include)',
            '<(os_include)/include',
            'src/include',
          ],
          'dependencies': [
            '../icu/icu.gyp:icuuc',
            '../zlib/zlib.gyp:zlib',
          ],
          'export_dependent_settings': [
            '../icu/icu.gyp:icuuc',
          ],
          'direct_dependent_settings': {
            'defines': [
              'LIBXML_STATIC',
            ],
            'include_dirs': [
              '<(os_include)/include',
              'src/include',
            ],
          },
          'conditions': [
            ['OS=="linux"', {
              'link_settings': {
                'libraries': [
                  # We need dl for dlopen() and friends.
                  '-ldl',
                ],
              },
            }],
            # http://www.xmlsoft.org/threads.html says that this is required
            # when using libxml from several threads, which can possibly happen
            # in chrome. On linux, this is picked up by transitivity from
            # pkg-config output from build/linux/system.gyp.
            ['OS=="mac" or OS=="android"', {'defines': ['_REENTRANT']}],
            ['OS=="win"', {
              'product_name': 'libxml2',
              # Disable unimportant 'unused variable' warning, and
              # signed/unsigned comparison warning. The signed/unsigned (4101)
              # is fixed upstream and can be removed eventually.
              # TODO(jschuh): http://crbug.com/167187 size_t -> int
              'msvs_disabled_warnings': [ 4018, 4101, 4267 ],
            }, {  # else: OS!="win"
              'product_name': 'xml2',
            }],
            ['clang == 1', {
              'xcode_settings': {
                'WARNING_CFLAGS': [
                  # libxml passes `const unsigned char*` through `const char*`.
                  '-Wno-pointer-sign',
                  # pattern.c and uri.c both have an intentional
                  # `for (...);` / `while(...);` loop. I submitted a patch to
                  # move the `'` to its own line, but until that's landed
                  # suppress the warning:
                  '-Wno-empty-body',
                ],
              },
              'cflags': [
                '-Wno-pointer-sign',
                '-Wno-empty-body',

                # See http://crbug.com/138571#c8
                '-Wno-ignored-attributes',
              ],
            }],
          ],
        }],
      ],
    },
  ],
}
<|endoftext|>


<commit_before>import os

from selenium import webdriver

class TestUserInterface(object):
    """Tests for Rogoto Web UI"""

    @classmethod
    def setup_class(cls):
        try:
            cls.username = os.environ['SAUCE_USERNAME']
            cls.key = os.environ['SAUCE_ACCESS_KEY']
            desired_capabilities = getattr(webdriver.DesiredCapabilities,
                                           os.environ['SAUCE_BROWSER'],
                                           None)
            if desired_capabilities is None:
                raise "Browser Capabilities Not Found"
            desired_capabilities['version'] = os.environ['SAUCE_BROWSER_VERSION']
            desired_capabilities['platform'] = os.environ['SAUCE_PLATFORM']
            desired_capabilities['name'] = 'Rogoto HTTP Server'
            desired_capabilities['tunnel-identifier'] = os.environ['TRAVIS_JOB_NUMBER']
            desired_capabilities['device-orientation'] = 'portrait'
            desired_capabilities['build'] = os.environ['TRAVIS_BUILD_NUMBER']
            desired_capabilities['tags'] = [os.environ['TRAVIS_PYTHON_VERSION'], 'CI']
            hub_url = "%s:%s@localhost:4445" % (cls.username, cls.key)

            cls.driver = webdriver.Remote(desired_capabilities=desired_capabilities,
                                          command_executor="http://%s/wd/hub" % hub_url)
        except Exception as e:
            print ("This following error was encounterd: %s" % e)
            cls.driver = webdriver.Firefox()

    @classmethod
    def teardown_class(cls):
        cls.driver.quit()

    def test_we_can_clear_things(self):
        self.driver.get('http://localhost:5000/logo')
        self.driver.find_element('id', 'code').send_keys("penup\npendown")
        self.driver.find_element('id', 'clear').click()
        assert "" == self.driver.find_element('id', 'code').get_attribute('value')
<commit_msg>adding in UI test for drawing<commit_after>import os

from selenium import webdriver

class TestUserInterface(object):
    """Tests for Rogoto Web UI"""

    @classmethod
    def setup_class(cls):
        try:
            cls.username = os.environ['SAUCE_USERNAME']
            cls.key = os.environ['SAUCE_ACCESS_KEY']
            desired_capabilities = getattr(webdriver.DesiredCapabilities,
                                           os.environ['SAUCE_BROWSER'],
                                           None)
            if desired_capabilities is None:
                raise "Browser Capabilities Not Found"
            desired_capabilities['version'] = os.environ['SAUCE_BROWSER_VERSION']
            desired_capabilities['platform'] = os.environ['SAUCE_PLATFORM']
            desired_capabilities['name'] = 'Rogoto HTTP Server'
            desired_capabilities['tunnel-identifier'] = os.environ['TRAVIS_JOB_NUMBER']
            desired_capabilities['device-orientation'] = 'portrait'
            desired_capabilities['build'] = os.environ['TRAVIS_BUILD_NUMBER']
            desired_capabilities['tags'] = [os.environ['TRAVIS_PYTHON_VERSION'], 'CI']
            hub_url = "%s:%s@localhost:4445" % (cls.username, cls.key)

            cls.driver = webdriver.Remote(desired_capabilities=desired_capabilities,
                                          command_executor="http://%s/wd/hub" % hub_url)
        except Exception as e:
            print ("This following error was encounterd: %s" % e)
            cls.driver = webdriver.Firefox()

    @classmethod
    def teardown_class(cls):
        cls.driver.quit()

    def setUp(self):
        self.driver.refresh()

    def test_we_can_clear_things(self):
        self.driver.get('http://localhost:5000/logo')
        self.driver.find_element('id', 'code').send_keys("penup\npendown")
        self.driver.find_element('id', 'clear').click()
        assert "" == self.driver.find_element('id', 'code').get_attribute('value')

    def test_we_can_draw_images(self):
        self.driver.get("http://localhost:5000/logo")
        self.driver.find_element('id', 'code').send_keys("pendown\nforward 20\nleft 30\nforward 100")
        self.driver.find_element('id', 'run').click()
        result = self.driver.execute_script('return arguments[0].toDataURL("image/png");',
                                             self.driver.find_element('id', 'logo'))
        assert 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASwAAACWCAYAAABkW7XSAAADQUlEQVR4nO3d1+u2cwDH8fdjPfaWmRkRoQgpI6NIQlZGSEJGiQihyIhEGUUiIwohImWEJDJCRgiRZPsbHFyHz8XRk+8dr1f9zt/3ydV9f7t+308BAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAy8261bGjIwD+yYrVudUv1YmDWwD+1oHVx9Vr1a5jUwDmbV09VX2Xn4HAglqjuqH6o7qyWjo2B2BZS6pTqx+rh6vNxuYAzNureqd6t9p7cAvArE2rh5q+VZ3W9C0LYKEsra5oOqe6sVpzbA7AvGOqb6unq20GtwDM2qV6tfqkOmhwC8CsDaq7q1+r85reWgdYKCtVF1a/VXdU643NAZh3aPV59VK10+AWgFnbVc9VX1dHDm4BmLVWdUvTawqXVquMzQFY1pLqzOqn6v5q47E5APP2rT6o3qr2GNwCMGuL6rHqh+qkwS0As1arrmk6p7q2Wn1sDsC8E6rvq8erLQe3AMzavXqz+rDab3ALwKyNqvuaRh/OqlYYmwOwrJWrS5rOqW6t1h6bAzDviOqr6vlq+8EtALN2rF6svqgOG9wCMGvd6vam2xQuarpdAWChrFCdU/1c3VNtODYHYN4BTSvKr1e7jU0BmLdV9WTTivJxY1MA5q1eXV/9WV1VrTo2B2DeKU17f49kRRlYUHs2rSi/V+0zuAVg1ibVg02X6Z2eFWVgAS2tLm/6d5qbsqIMLKijq2+qZ6ptB7cAzNq5eqX6tDp4cAvArPWru5pWlM/PijKwgFasLmh6UN3Z9OACWDiHVJ9VLzf9FARYONtVzzYdqh81uAVg1prVzU2vKVyWFWVgAS2pzmi69uWBrCgDC2rf6v3q7awoAwtq8+rRphXlkwe3AMxatbq66ZzquqwoAwvq+KYV5SeaLtYDWDi7VW9UH1X7D24BmLVRdW/TivLZWVEGFtDK1cXV79Vt1Tpjc4D/km+X89+X1QvVDv/mhwD+H5b3A+vwfzcfAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABvgLIgmGdaYBIUUAAAAASUVORK5CYII=' == result
<|endoftext|>


<commit_before># This file is part of cclib (http://cclib.sf.net), a library for parsing
# and interpreting the results of computational chemistry packages.
#
# Copyright (C) 2007, the cclib development team
#
# The library is free software, distributed under the terms of
# the GNU Lesser General Public version 2.1 or later. You should have
# received a copy of the license along with cclib. You can also access
# the full license online at http://www.gnu.org/copyleft/lgpl.html.

import os
import logging
import unittest

# If numpy is not installed, try to import Numeric instead.
try:
    import numpy
except ImportError:
    import Numeric as numpy

from testall import getfile
from cclib.method import CDA
from cclib.parser import Gaussian

def main(log=True):
    data1, logfile1 = getfile(Gaussian, "CDA", "BH3CO-sp.log")
    data2, logfile2 = getfile(Gaussian, "CDA", "BH3.log")
    data3, logfile3 = getfile(Gaussian, "CDA", "CO.log")
    fa = CDA(data1)
    if not log:
        fa.logger.setLevel(logging.ERROR)
    fa.calculate([data2, data3])

    return fa

def printResults():
    fa = main()

    print("       d       b       r")
    print("---------------------------")

    spin = 0
    for i in range(len(fa.donations[0])):

        print("%2i: %7.3f %7.3f %7.3f" % (i,
                                            fa.donations[spin][i],
                                            fa.bdonations[spin][i],
                                            fa.repulsions[spin][i]))

    print("---------------------------")
    print("T:  %7.3f %7.3f %7.3f" % (fa.donations[0].sum(),
                                        fa.bdonations[0].sum(),
                                        fa.repulsions[0].sum()))
    print("\n\n")

class CDATest(unittest.TestCase):
    def runTest(self):
        """Testing CDA results against Frenking's code"""
        fa = main(log=False)

        donation = fa.donations[0].sum()
        bdonation = fa.bdonations[0].sum()
        repulsion = fa.repulsions[0].sum()

        self.assertAlmostEqual(donation, 0.181, 3)
        self.assertAlmostEqual(bdonation, 0.471, 3)
        self.assertAlmostEqual(repulsion, -0.334, 3)

tests = [CDATest]

if __name__ == "__main__":
    printResults()
    unittest.TextTestRunner(verbosity=2).run(unittest.makeSuite(CDATest))
<commit_msg>CDA test: update copyright to 2014<commit_after># This file is part of cclib (http://cclib.sf.net), a library for parsing
# and interpreting the results of computational chemistry packages.
#
# Copyright (C) 2007-2014, the cclib development team
#
# The library is free software, distributed under the terms of
# the GNU Lesser General Public version 2.1 or later. You should have
# received a copy of the license along with cclib. You can also access
# the full license online at http://www.gnu.org/copyleft/lgpl.html.

import os
import logging
import unittest

# If numpy is not installed, try to import Numeric instead.
try:
    import numpy
except ImportError:
    import Numeric as numpy

from testall import getfile
from cclib.method import CDA
from cclib.parser import Gaussian

def main(log=True):
    data1, logfile1 = getfile(Gaussian, "CDA", "BH3CO-sp.log")
    data2, logfile2 = getfile(Gaussian, "CDA", "BH3.log")
    data3, logfile3 = getfile(Gaussian, "CDA", "CO.log")
    fa = CDA(data1)
    if not log:
        fa.logger.setLevel(logging.ERROR)
    fa.calculate([data2, data3])

    return fa

def printResults():
    fa = main()

    print("       d       b       r")
    print("---------------------------")

    spin = 0
    for i in range(len(fa.donations[0])):

        print("%2i: %7.3f %7.3f %7.3f" % (i,
                                            fa.donations[spin][i],
                                            fa.bdonations[spin][i],
                                            fa.repulsions[spin][i]))

    print("---------------------------")
    print("T:  %7.3f %7.3f %7.3f" % (fa.donations[0].sum(),
                                        fa.bdonations[0].sum(),
                                        fa.repulsions[0].sum()))
    print("\n\n")

class CDATest(unittest.TestCase):
    def runTest(self):
        """Testing CDA results against Frenking's code"""
        fa = main(log=False)

        donation = fa.donations[0].sum()
        bdonation = fa.bdonations[0].sum()
        repulsion = fa.repulsions[0].sum()

        self.assertAlmostEqual(donation, 0.181, 3)
        self.assertAlmostEqual(bdonation, 0.471, 3)
        self.assertAlmostEqual(repulsion, -0.334, 3)

tests = [CDATest]

if __name__ == "__main__":
    printResults()
    unittest.TextTestRunner(verbosity=2).run(unittest.makeSuite(CDATest))
<|endoftext|>


<commit_before>from flask import Blueprint, jsonify, request
from models import Sensor
from forms import SensorForm
from . import db

sensors = Blueprint('sensors', __name__,
    template_folder='templates')

@sensors.route('/')
def index():
    return "sensor blueprint"

@sensors.route('/all')
def get_all_sensors():
    return jsonify(sensors=[val.serialise for val in Sensor.query.all()])

@sensors.route('/register/<sensor_name>', methods=['POST'])
def register(sensor_name):
    form = SensorForm(request.form)
    if form.validate():
        return "Sensor: {0} added".format(sensor_name)
    #sensor = Sensor(sensor_name, "description place holder")
    #db.session.add(sensor)
    #db.session.commit()
    return "nope"

<commit_msg>actually validates<commit_after>from flask import Blueprint, jsonify, request, render_template
from models import Sensor
from forms import SensorForm
from . import db

sensors = Blueprint('sensors', __name__,
    template_folder='templates')

@sensors.route('/')
def index():
    return "sensor blueprint"

@sensors.route('/all')
def get_all_sensors():
    return jsonify(sensors=[val.serialise for val in Sensor.query.all()])

@sensors.route('/register', methods=['POST'])
def register():
    form = SensorForm(request.form)
    if form.validate():
        #sensor = Sensor(sensor_name, "description place holder")
        #db.session.add(sensor)
        #db.session.commit()
        return "valid"
        #return 201 - created
        #return 202 if already exists
    return "invalid", 400

<|endoftext|>


<commit_before>from collections import defaultdict
from itertools import chain
import unittest

from apriori import (
    subsets,
    returnItemsWithMinSupport,
)

class AprioriTest(unittest.TestCase):
    def test_subsets_should_return_empty_subsets_if_input_empty_set(self):
        result = tuple(subsets(frozenset([])))

        self.assertEqual(result, ())

    def test_subsets_should_return_non_empty_subsets(self):
        result = tuple(subsets(frozenset(['beer', 'rice'])))

        self.assertEqual(result[0], ('beer',))
        self.assertEqual(result[1], ('rice',))
        self.assertEqual(result[2], ('beer', 'rice',))

    def test_return_items_with_min_support(self):
        itemSet = set([
            frozenset(['apple']),
            frozenset(['beer']),
            frozenset(['chicken']),
            frozenset(['mango']),
            frozenset(['milk']),
            frozenset(['rice'])
        ])
        transactionList = [
            frozenset(['beer', 'rice', 'apple', 'chicken']),
            frozenset(['beer', 'rice', 'apple']),
            frozenset(['beer', 'apple']),
            frozenset(['mango', 'apple']),
            frozenset(['beer', 'rice', 'milk', 'chicken']),
            frozenset(['beer', 'rice', 'milk']),
            frozenset(['beer', 'milk']),
            frozenset(['mango', 'milk'])
        ]
        minSupport = 0.5
        freqSet = defaultdict(int)

        result = returnItemsWithMinSupport(
            itemSet,
            transactionList,
            minSupport,
            freqSet
        )

        expected = set([
            frozenset(['milk']),
            frozenset(['apple']),
            frozenset(['beer']),
            frozenset(['rice'])
        ])
        self.assertEqual(result, expected)

        expected = defaultdict(
            int,
            {
                frozenset(['apple']): 4,
                frozenset(['beer']): 6,
                frozenset(['chicken']): 2,
                frozenset(['mango']): 2,
                frozenset(['milk']): 4,
                frozenset(['rice']): 4
            }
        )
        self.assertEqual(freqSet, expected)

if __name__ == '__main__':
    unittest.main()
<commit_msg>Test joining set and get the n-element itemsets<commit_after>from collections import defaultdict
from itertools import chain
import unittest

from apriori import (
    joinSet,
    returnItemsWithMinSupport,
    subsets,
)

class AprioriTest(unittest.TestCase):
    def test_subsets_should_return_empty_subsets_if_input_empty_set(self):
        result = tuple(subsets(frozenset([])))

        self.assertEqual(result, ())

    def test_subsets_should_return_non_empty_subsets(self):
        result = tuple(subsets(frozenset(['beer', 'rice'])))

        self.assertEqual(result[0], ('beer',))
        self.assertEqual(result[1], ('rice',))
        self.assertEqual(result[2], ('beer', 'rice',))

    def test_return_items_with_min_support(self):
        itemSet = set([
            frozenset(['apple']),
            frozenset(['beer']),
            frozenset(['chicken']),
            frozenset(['mango']),
            frozenset(['milk']),
            frozenset(['rice'])
        ])
        transactionList = [
            frozenset(['beer', 'rice', 'apple', 'chicken']),
            frozenset(['beer', 'rice', 'apple']),
            frozenset(['beer', 'apple']),
            frozenset(['mango', 'apple']),
            frozenset(['beer', 'rice', 'milk', 'chicken']),
            frozenset(['beer', 'rice', 'milk']),
            frozenset(['beer', 'milk']),
            frozenset(['mango', 'milk'])
        ]
        minSupport = 0.5
        freqSet = defaultdict(int)

        result = returnItemsWithMinSupport(
            itemSet,
            transactionList,
            minSupport,
            freqSet
        )

        expected = set([
            frozenset(['milk']),
            frozenset(['apple']),
            frozenset(['beer']),
            frozenset(['rice'])
        ])
        self.assertEqual(result, expected)

        expected = defaultdict(
            int,
            {
                frozenset(['apple']): 4,
                frozenset(['beer']): 6,
                frozenset(['chicken']): 2,
                frozenset(['mango']): 2,
                frozenset(['milk']): 4,
                frozenset(['rice']): 4
            }
        )
        self.assertEqual(freqSet, expected)

    def test_join_set_and_get_two_element_itemsets(self):
        itemSet = set([
            frozenset(['apple']),
            frozenset(['beer']),
            frozenset(['chicken']),
            frozenset(['mango']),
            frozenset(['milk']),
            frozenset(['rice'])
        ])

        result = joinSet(itemSet, 2)

        expected = set([
            frozenset(['chicken', 'mango']),
            frozenset(['rice', 'apple']),
            frozenset(['beer', 'apple']),
            frozenset(['rice', 'milk']),
            frozenset(['beer', 'rice']),
            frozenset(['chicken', 'apple']),
            frozenset(['beer', 'milk']),
            frozenset(['chicken', 'rice']),
            frozenset(['beer', 'mango']),
            frozenset(['beer', 'chicken']),
            frozenset(['apple', 'milk']),
            frozenset(['mango', 'milk']),
            frozenset(['mango', 'apple']),
            frozenset(['rice', 'mango']),
            frozenset(['chicken', 'milk'])
        ])
        self.assertEqual(result, expected)

    def test_join_set_and_get_three_element_itemsets(self):
        itemSet = set([
            frozenset(['apple', 'beer']),
            frozenset(['beer']),
            frozenset(['chicken']),
            frozenset(['mango']),
            frozenset(['milk']),
            frozenset(['rice'])
        ])

        result = joinSet(itemSet, 3)

        expected = set([
            frozenset(['beer', 'mango', 'apple']),
            frozenset(['beer', 'apple', 'chicken']),
            frozenset(['beer', 'apple', 'milk']),
            frozenset(['beer', 'rice', 'apple'])
        ])
        self.assertEqual(result, expected)

if __name__ == '__main__':
    unittest.main()
<|endoftext|>